修改的Interop Excel中打开现有文件(Modify Interop Excel for O

2019-10-20 17:49发布

我使用Excel互操作的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.");
}

它工作正常,但我需要打开现有的文件做,以避免打印页边距的重新配置同样的事情。 我检查了其他类似的问题,并试图申请“工作簿= oXL.Workbooks.Open(”路径“ ...);” 但它可以使它发挥作用。 有什么想法吗?

Answer 1:

要打开文件使用Open方法。

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

在你的方法结束时,你应该做一个清理所有的互操作变量:

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

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


文章来源: Modify Interop Excel for Opening Existing File