递归错误访问冲突

时间:2015-11-18 20:35:49

标签: c# recursion export-to-excel access-violation worksheet

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

但我的代码仅适用于小型DataTables

1 个答案:

答案 0 :(得分:0)

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

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