C#:如何打开和关闭Excel工作簿? [英] C#: How can I open and close an Excel workbook?

查看:2027
本文介绍了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 中的文件,以便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工作簿?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆