【问题标题】:Recursive error access violation递归错误访问冲突
【发布时间】: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


【解决方案1】:

我不能使用这种递归模式。

我的解决方案是 EPPlus.dll

using OfficeOpenXml;

这个方法:

DataTable dt = Conversao.ConvertTo(list);
if (dt == null || dt.Columns.Count == 0)
    throw new Exception("ExportToExcel: Null or empty input table!\n");

OfficeOpenXml.ExcelPackage excel = new ExcelPackage();

ExcelWorksheet worksheet = excel.Workbook.Worksheets.Add("Plan 1");
worksheet.Cells["A1"].LoadFromDataTable(dt, true);

for (var i = 0; i < dt.Columns.Count; i++)
{
    if (dt.Columns[i].DataType == System.Type.GetType("System.DateTime"))
    {
        worksheet.Column(i + 1).Style.Numberformat.Format = "dd/mm/yyyy hh:mm:ss";
    }
}

Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=rel.xlsx");

Response.ContentType = "application/vnd.ms-excel";
Response.ContentEncoding = System.Text.Encoding.Default;

Response.Cache.SetCacheability(HttpCacheability.NoCache);

System.IO.MemoryStream stream = new System.IO.MemoryStream();
excel.SaveAs(stream);

stream.WriteTo(Response.OutputStream);

Response.End();

感谢 grek40

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-28
    • 1970-01-01
    相关资源
    最近更新 更多