本文介绍了C#:如何打开和关闭Excel工作簿?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有人知道如何简单地打开和关闭Excel工作簿?

我不需要从文件中读取任何数据我只需要打开和关闭它。 (*)

I don't need to read any data from the file, I just need to open and close it. (*)

我猜想我需要引用Microsoft.Office.Interop.Excel程序集。

I'm guessing that I'll need to reference the Microsoft.Office.Interop.Excel assembly.

*原因:我已经使用第三方库(Aspose)配置了数据透视表信息。现在我需要阅读生成的数据透视表。

*Reason: I've already configured pivot table information with a 3rd party library (Aspose). Now I need to read the generated pivot table.

不幸的是,Aspose库在运行时无法生成数据透视表。它需要某人以便Excel可以生成数据透视表值。

Unfortunately, the Aspose library can't generate the pivot table at runtime. It needs someone to open the file with Excel so that Excel can generate the pivot table values.

推荐答案

引用Microsoft.Office.Interop.Excel还要确保清理在最后。

after referencing Microsoft.Office.Interop.Excel also Make sure to clean up in the finally.

using Excel = Microsoft.Office.Interop.Excel;

        Excel.ApplicationClass _Excel;
        Excel.Workbook WB;
        Excel.Worksheet WS;

    try
        {

        _Excel = new Microsoft.Office.Interop.Excel.ApplicationClass();
        WB = _Excel.Workbooks.Open("FILENAME",
            Type.Missing, Type.Missing, Type.Missing, Type.Missing,
            Type.Missing, Type.Missing, Type.Missing, Type.Missing,
            Type.Missing, Type.Missing, Type.Missing, Type.Missing,
            Type.Missing, Type.Missing);

            //do something

        }
        catch (Exception ex)
        {
            WB.Close(false, Type.Missing, Type.Missing);

            throw;
        }
        finally
        {
            GC.Collect();
            GC.WaitForPendingFinalizers();

            System.Runtime.InteropServices.Marshal.FinalReleaseComObject(WB);

            System.Runtime.InteropServices.Marshal.FinalReleaseComObject(_Excel);


        }

这篇关于C#:如何打开和关闭Excel工作簿?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 22:13