【问题标题】:Sudden Code Failure in Visual Studio Express 2010Visual Studio Express 2010 中的突然代码故障
【发布时间】:2012-08-02 20:30:14
【问题描述】:

这段代码突然停止输出 Excel 文件。它正在将 DataTable dtOutput 转换为 Excel 文件:

if (dtOutput.Rows.Count > 0)
{
    DataView dv = dtOutput.DefaultView;
    dv.Sort = "Outage Start Time";
    dtOutput = dv.ToTable();
    // Populates a column of the table
    dtOutput = addIncidentCounts(dtOutput);

    Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
    Workbook wb = xlApp.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
    Worksheet ws = (Worksheet)wb.Worksheets[1];
    ws.Name = "Retail Network Tracking Log";

    int col = 1;
    foreach (DataColumn column in dtOutput.Columns)
    {
        ws.Cells[1, col].Value2 = column.ColumnName;
        col++;
    }

    for (int i = 0; i < dtOutput.Rows.Count; i++)
    {
        for (int j = 0; j < dtOutput.Columns.Count; j++)
        {
            ws.Cells[i + 2, j + 1].Value2 = dtOutput.Rows[i][j];
        }
    }

    foreach (Range range in ws.UsedRange.Columns)
    {
        range.HorizontalAlignment = XlHAlign.xlHAlignLeft;
        range.Columns.AutoFit();
    }

    Range rangeE = ws.get_Range("E:E", Type.Missing);
    rangeE.NumberFormat = "d-mmm-yyyy hh:mm:ss";

    Range rangeF = ws.get_Range("F:F", Type.Missing);
    rangeF.NumberFormat = "d-mmm-yyyy hh:mm:ss";

    wb.Close(false, false, Type.Missing);
    xlApp.Quit();
    Marshal.ReleaseComObject(wb);
    Marshal.ReleaseComObject(xlApp);

    this.Close();
}

它已经完美运行了数周。我没有对其进行任何更改。我重新启动了VS,重新启动了计算机,最后重新安装了VS,但我仍然没有得到任何输出。我也通过调试器运行了它,代码肯定正在执行并获得所有正确的值。我被难住了。

【问题讨论】:

  • 如果没有有关您遇到的错误的某种信息,将无法帮助您。话虽这么说,如果我不得不猜测我会说它是权限问题,或者目录结构问题,或者什么
  • 我没有看到您在关闭 Excel 之前将工作簿保存在哪里?
  • ...或者您在错误的位置查找已保存的工作簿?你试过用固定的绝对路径显式保存吗?
  • Workbook.Close() 调用看起来很奇怪。您为 SaveChanges 参数传递 false,为 Filename 参数传递 false

标签: excel com-interop excel-interop


【解决方案1】:

Hans Passant 是对的。关闭的调用需要是:

wb.Close(true, saveDirectory + "\\" + reportName, false);

现在真正的谜团是这段代码最初是如何工作的!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-02
    • 2011-06-30
    • 2011-07-05
    相关资源
    最近更新 更多