递归错误访问冲突

Recursive error access violation

我在 C# 上做了一个 class 以使用数据表打开 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 它工作得很好,但更多的是应用程序停止并且在控制台上显示错误 'Access Violation':

The program '[3396] iisexpress.exe: Program Trace' has exited with code 0 (0x0).

The program '[3396] iisexpress.exe' has exited with code -1073741819 (0xc0000005) 'Access violation'.

我试试这个:

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

但我的代码只适用于小数据表

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

我的解决方案是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