2014-04-09 79 views
1

我可以用2個工作表正確地創建一個Excel,我可以寫一個DataTable的數據1頁,我想同樣的數據寫入表2Sheet 2似乎爲空白。爲什麼「Sheet 2」爲空?拖到新的工作表添加到Excel與互操作性

這裏是我的代碼:

Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application(); 
if (xlApp == null) 
{ 
    Console.WriteLine("EXCEL could not be started. Check that your office installation and project references are correct."); 
    return; 
} 
xlApp.Visible = true; 

Microsoft.Office.Interop.Excel.Workbook wb = xlApp.Workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet); 
Microsoft.Office.Interop.Excel.Worksheet ws = (Microsoft.Office.Interop.Excel.Worksheet)wb.Worksheets[1]; 

{ 
    if (ws == null) 
    { 
     Console.WriteLine("Worksheet could not be created. Check that your office installation and project references are correct."); 
    } 

    Microsoft.Office.Interop.Excel.Range aRange = ws2.get_Range("C1", "C7"); 

    for (int i = 0; i < main_dt.Columns.Count; i++) 
    { 
     ws.Cells[1, i + 1] = main_dt.Columns[i].ColumnName; 
     aRange = (Microsoft.Office.Interop.Excel.Range)ws.Cells[1, i + 1]; 
     aRange.Interior.ColorIndex = 15; 
     aRange.Font.Bold = true; 
    } 

    for (int r = 0; r < main_dt.Rows.Count; r++) 
    { 
     for (int i = 0; i < main_dt.Columns.Count; i++) 
     { 
      ws.Cells[r + 2, i + 1] = main_dt.Rows[r][i].ToString(); 
     }  
    } 
} 

// WORKSHEET 2 ****************** 
wb.Sheets.Add(); 
Microsoft.Office.Interop.Excel.Worksheet ws2 = (Microsoft.Office.Interop.Excel.Worksheet)wb.Worksheets[2]; 

{ 
    if (ws2 == null) 
    { 
     Console.WriteLine("Worksheet could not be created. Check that your office installation and project references are correct."); 
    } 

    Microsoft.Office.Interop.Excel.Range aRange = ws2.get_Range("C1", "C7"); 

    for (int i = 0; i < main_dt.Columns.Count; i++) 
    { 
     ws2.Cells[1, i + 1] = main_dt.Columns[i].ColumnName; 
     aRange = (Microsoft.Office.Interop.Excel.Range)ws2.Cells[1, i + 1]; 
     aRange.Interior.ColorIndex = 15; 
     aRange.Font.Bold = true;  
    } 

    for (int r = 0; r < main_dt.Rows.Count; r++) 
    { 
     for (int i = 0; i < main_dt.Columns.Count; i++) 
     { 
      ws2.Cells[r + 2, i + 1] = main_dt.Rows[r][i].ToString(); 
     }  
    } 
} 
+0

根據您的Excel設置,但在默認情況下的Excel工作簿與3張創建。沒有必要添加另一張紙。 '工作表ws2 = ws.Sheets [2]作爲工作表;'應該足以獲得對Sheet2的引用。你的代碼應該寫在我看到的Sheet1和Sheet2中......同樣在if(ws == null)'上面有一個額外的'{'開頭括號 - 是有意的嗎?另外,第一個'aRange'不應該是'ws.get_Range'而不是'ws2'? –

+0

默認Excel版本<2013 –

回答

5

相反的:

wb.Sheets.Add(); 
Microsoft.Office.Interop.Excel.Worksheet ws2 = 
         (Microsoft.Office.Interop.Excel.Worksheet)wb.Worksheets[2]; 

嘗試:

Microsoft.Office.Interop.Excel.Worksheet ws2 = 
         (Microsoft.Office.Interop.Excel.Worksheet)wb.Sheets.Add(); 
+0

但是默認情況下,新工作簿中有3張。當你可以用'wb.Sheets [2];'引用已經存在的工作表時,爲什麼還要添加另一個工作表? –

+1

@mehow Excel 2013默認有1張 –

+0

@BenAaronson好點,但我很抱歉,我可能錯過了這裏的一些東西,但是Excel 2013提到了什麼?即使它是2013年這兩條線幾乎是相同的....我不認爲這解決了這個問題,雖然 –