Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.6k views
in Technique[技术] by (71.8m points)

c# - Excel Interop Behavior .NET Core versus .NET Framework

I am trying to use Microsoft.Office.Interop.Excel to open several spreadsheets and read data from them. I've run into a common problem with interop: Excel fails to close after the program exits. I am not new to using interop with .NET Framework, but this is my first go with .NET Core.

I have narrowed down the problem to a difference between the way .NET Core and .NET Framework work with interop. Here is my simplified code:

try
{
    _excel = new Excel.Application();
    _excel.DisplayAlerts = false;
    _wbs = _excel.Workbooks;

    _wb = _wbs.Open(file.FullName);

    // PROBLEM HERE
    _ws = _wb.Worksheets["Sheet1"];

    _wb.Close();

}
catch (Exception ex)
{
    Console.WriteLine(ex.Message);
}
finally
{
    if (_ws != null) System.Runtime.InteropServices.Marshal.ReleaseComObject(_ws);
    if (_wbs != null) System.Runtime.InteropServices.Marshal.ReleaseComObject(_wbs);
    if (_excel != null)
    {
        _excel.DisplayAlerts = true;
        _excel.Quit();
        System.Runtime.InteropServices.Marshal.ReleaseComObject(_excel);
    }
}

This code works as expected if you run it in a .NET Framework program. If you use .NET Core, the program will exit and Excel will continue to run in the background UNLESS you comment out the line below the "PROBLEM HERE" comment. There are no errors in any case.

I am using the latest versions of interop for both and yes they are different versions. The framework version is 15.0.0.0 and the .NET Core version is 1.9.

I know that .NET Core is way of the future so I'd prefer to use that, but interop doesn't seem to work well with it. Has anyone seen this before? Is there a better way or should I simply avoid .NET Core for now?

UPDATE:

To answer some questions: The version of the interop is 15.0.0.0 for the Framework version of the code and 1.9 for the .NET Core version.

It's not a sever application. I said I'm trying to load and read some Excel spreadsheets. I didn't pick Excel spreadsheets. The data is already in Excel spreadsheets. If it were CSV or I could get it in CSV I would. That's not an option.

The Framework version of the code works. I didn't use "using" because this is a toy version of the code to illustrate the problem.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神解答

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...