关闭Excel工作簿 [英] Closing an Excel Workbook

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

问题描述

我有一些代码可以打开xls工作簿;

I have a bit of code that opens an xls workbook;

Excel.Workbooks workBooks;
workBooks = excelApp.Workbooks;
workbook = workBooks.Open(sourceFilePath + sourceFileName + ".xls");

然后我得到了工作表;

I then get the work sheet;

worksheets = workbook.Worksheets;
worksheet = worksheets.get_Item("Standard");

然后我将文件另存为csv;

I then save the file as a csv;

worksheet.SaveAs(sourceFilePath + sourceFileName + ".csv", Excel.XlFileFormat.xlCSVWindows, Type.Missing, Type.Missing, false, false, Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing);

然后我尝试关闭工作簿;

Then I try to close the workbook;

Marshal.FinalReleaseComObject(worksheet);
Marshal.FinalReleaseComObject(worksheets);
workbook.Close();
Marshal.FinalReleaseComObject(workbook);

但是,每次我到达line workbook.Close()时,系统都会停止.

However, every time i get to the line workbook.Close(), the system stops.

如果我不执行另存为,则工作簿将关闭.

If I do not do the SaveAs then the workbook closes just fine.

如何关闭工作簿?

修改

看任务管理器,我发现Excel.exe仍在运行.关闭它会在我的代码中产生错误.

Looking at Task Manager shows me that Excel.exe is still running. Closing it will produce an error in my code.

修改2

我已经看到了引用的SO帖子,但是它并不能解决问题.

I have already seen the referenced SO post and it did not solve the issue.

推荐答案

这是解决方案

第一: using EXCEL = Microsoft.Office.Interop.Excel;

,然后path是您的excel所在的位置.

and then, path is where your excel locates.

        EXCEL.Application excel = new EXCEL.Application();
        try
        {
            EXCEL.Workbook book = excel.Application.Workbooks.Open(path);
            EXCEL.Worksheet sheet = book.Worksheets[1];
            // yout operation

        }
        catch (Exception ex) { MessageBox.Show("readExcel:" + ex.Message); }
        finally
        {
            KillExcel(excel);
            System.Threading.Thread.Sleep(100);
        }



    [DllImport("User32.dll")]
    public static extern int GetWindowThreadProcessId(IntPtr hWnd, out int ProcessId);
    private static void KillExcel(EXCEL.Application theApp)
    {
        int id = 0;
        IntPtr intptr = new IntPtr(theApp.Hwnd);
        System.Diagnostics.Process p = null;
        try
        {
            GetWindowThreadProcessId(intptr, out id);
            p = System.Diagnostics.Process.GetProcessById(id);
            if (p != null)
            {
                p.Kill();
                p.Dispose();
            }
        }
        catch (Exception ex)
        {
            System.Windows.Forms.MessageBox.Show("KillExcel:" + ex.Message);
        }
    }

这篇关于关闭Excel工作簿的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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