1
我做了C#类与数据表中打开的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行它的工作非常出色,但更多的则该应用程序停止并在控制台上显示错误'访问冲突':
该程序'[i386] ix.exe:程序跟踪'有ex与代码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左右的递归深度,每个递归步骤都需要一部分堆栈......也许您可以测量递归深度并调整代码,如果那样的话问题出现? – grek40
但我怎么样? –
如果您不知道如何确定递归深度,请不要使用递归。找到不同的解决方案,使用循环代替递归。 – grek40