修改Interop Excel以打开现有文件

时间:2014-08-15 18:52:08

标签: c# excel-interop

我正在使用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“,...);”但它可以使它工作。有什么想法吗?

1 个答案:

答案 0 :(得分:2)

要使用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;
            }