【问题标题】:Modify Interop Excel for Opening Existing File修改 Interop Excel 以打开现有文件
【发布时间】:2014-08-15 18:52:08
【问题描述】:

我正在使用 Excel Interop for C# 将 datagridview 导出到 Excel 并打印出来。我正在使用此代码:

try
{
    Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();                                
    excel.Application.Workbooks.Add(true);

    int ColumnIndex = 0;
    int rowIndex = -1;
    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        rowIndex++;
        ColumnIndex = 0;

        foreach (DataGridViewColumn col in dataGridView1.Columns)
        {
            ColumnIndex++;
            excel.Cells[rowIndex + 1, ColumnIndex] = row.Cells[col.Name].Value;
        }
    }                

    excel.Visible = true;
    excel.DisplayAlerts = false;                
    Worksheet worksheet = (Worksheet)excel.ActiveSheet;
    worksheet.Activate();
    worksheet.Cells.Style.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
    worksheet.Range[worksheet.Cells[1, 1], worksheet.Cells[1, 7]].Merge();
    worksheet.Range[worksheet.Cells[2, 1], worksheet.Cells[2, 7]].Merge();
    worksheet.Range[worksheet.Cells[3, 1], worksheet.Cells[3, 7]].Merge();
    worksheet.Range[worksheet.Cells[4, 1], worksheet.Cells[4, 4]].Merge();      
    worksheet.Cells[1, 1].Font.Bold = true;
    worksheet.Range["A1"].Cells.Font.Size = 15;
    worksheet.Range["A4"].Cells.Font.Size = 15;
    worksheet.Range["B7"].Cells.Font.Size = 15;
    worksheet.Range["B8"].Cells.Font.Size = 15;
    worksheet.Range["B9"].Cells.Font.Size = 15;
    worksheet.Range["A11"].Cells.Font.Size = 15;
    worksheet.Range["B13"].Cells.Font.Size = 15;

    worksheet.PrintOut(Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

    GC.Collect();
    GC.WaitForPendingFinalizers();

    excel.Quit();
}

catch (Exception ex)
{
    MessageBox.Show("Error de exportación.");
}

它工作正常,但我需要打开一个现有文件来做同样的事情,以避免重新配置打印边距。我检查了其他类似的问题并尝试应用“workBook = oXL.Workbooks.Open("path", ...);"但它可以使它工作。有什么想法吗?

【问题讨论】:

  • 当您使用Open 时究竟会发生什么?此外,如果您在异常消息中包含 ex.ToString(),您会发现更容易解决问题。

标签: c# excel-interop


【解决方案1】:

要打开文件,请使用 open 方法。

        Microsoft.Office.Interop.Excel.Workbooks wkbks = null;
        Microsoft.Office.Interop.Excel.Workbook wkbk = null;
        wkbks = excel.Workbooks;
        wkbk = wkbks.Open(xlsFileName);

在您的方法结束时,您应该对所有互操作变量执行cleanup

            if (wkbk != null)
            {
                try
                {
                    wkbk.Close(false);
                }
                catch
                {
                }

                Marshal.FinalReleaseComObject(wkbk);
                wkbk = null;
            }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-26
    • 2012-10-14
    • 1970-01-01
    • 2010-11-09
    相关资源
    最近更新 更多