gpt4 book ai didi

c# - 拖曳以使用互操作将新工作表添加到 Excel

转载 作者:太空宇宙 更新时间:2023-11-03 20:06:40 25 4
gpt4 key购买 nike

我可以使用 2 个工作表正确创建 Excel,我可以将 DataTable 的数据写入工作表 1,我想将相同的数据写入工作表 2 但是 < em>Sheet 2 似乎是空白的。为什么“工作表 2” 是空白的?

这是我的代码:

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

最佳答案

代替:

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

关于c# - 拖曳以使用互操作将新工作表添加到 Excel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22961680/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com