我可以用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 –