简体   繁体   English

通过互操作将新工作表添加到Excel中

[英]Tow to add a new worksheet to Excel with interop

I can create an Excel properly with 2 worksheets, and I can write a DataTable's data to Sheet 1 and I want to write the same data to Sheet 2 but Sheet 2 seems blank. 我可以使用2个工作表正确创建一个Excel,并且可以将DataTable的数据写入工作表1,并且我想将相同的数据写入工作表2,但工作表2似乎是空白。 Why "Sheet 2" is blank? 为什么“ Sheet 2”为空白?

Here is my code: 这是我的代码:

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();
        }    
    }
}

Instead of: 代替:

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

try: 尝试:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM