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