【发布时间】:2015-11-18 20:35:49
【问题描述】:
我在 C# 上上了一堂课,用 DataTable 打开 Excel:
var excelApp = new ExcelInterop.Application();
excelApp.Workbooks.Add();
ExcelInterop._Worksheet workSheet = excelApp.ActiveSheet;
for (int i = 0; i < dt.Columns.Count; i++)
{
workSheet.Cells[1, (i + 1)] = dt.Columns[i].ColumnName;
}
ExcelRecursive(dt, workSheet, 0, 0);
excelApp.Visible = true;
方法递归:
public void ExcelRecursive(DataTable dt, ExcelInterop._Worksheet ws, int i, int j)
{
ws.Cells[(i + 2), (j + 1)] = dt.Rows[i][j];
if (j + 1 < dt.Columns.Count)
ExcelRecursive(dt, ws, i, j + 1);
else if (i + 1 < dt.Rows.Count)
ExcelRecursive(dt, ws, i + 1, 0);
}
具有 70 行的 DataTables 运行良好,但更多的是应用程序停止并且在控制台上显示错误“访问冲突”:
程序“[3396] iisexpress.exe:程序跟踪”已退出,代码为 0 (0x0)。
程序“[3396] iisexpress.exe”已退出,代码为 -1073741819 (0xc0000005)“访问冲突”。
我试试这个:
for (int i = 0; i < dt.Rows.Count; i++)
{
// to do: format datetime values before printing
for (int j = 0; j < dt.Columns.Count; j++)
{
workSheet.Cells[(i + 2), (j + 1)] = dt.Rows[i][j];
}
}
还有这个:
public ExcelInterop._Worksheet ExcelRecursive(DataTable dt, ExcelInterop._Worksheet ws, int i, int j)
{
ws.Cells[(i + 2), (j + 1)] = dt.Rows[i][j];
if (j + 1 < dt.Columns.Count)
return ExcelRecursive(dt, ws, i, j + 1);
else if (i + 1 < dt.Rows.Count)
return ExcelRecursive(dt, ws, i + 1, 0);
else
return ws;
}
但我的代码只适用于小数据表
【问题讨论】:
-
据我所知,您对工作表中的每个单元格都有一个递归调用。例如,具有 256 列和 70 行的工作表导致递归深度约为 18000,并且每个递归步骤都需要堆栈的一部分......也许你可以测量你的递归深度并调整你的代码,如果那是问题?
-
如果您不知道如何确定递归深度,请不要使用递归。找到问题的不同解决方案,使用循环而不是递归。
标签: c# recursion export-to-excel access-violation worksheet