如何关闭存储在服务器中的 Excel 文件?
How to Close An Excel File That is Stored In the Server?
我目前正在开发一个将数据插入 Excel 文件并随后将其关闭的应用程序。 Excel 文件已经存在并存储在服务器的一个目录中。每次我 运行 应用程序都会进入目录,打开 Excel 文件,然后插入数据。
// The codes below are executed after opening the Excel file, inserting data, and saving it.
using xl = Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;
string report = "Report.XLSX";
object obj = Marshal.GetActiveObject("Excel.Application");
xl.Application application = obj as xl.Application;
xl.Workbooks workbooks = application.Workbooks;
foreach (xl.Workbook workbook in workbooks)
{
if (workbook.Name == report)
{
workbook.Close();
}
}
GC.WaitForPendingFinalizers();
if (workbooks != null)
Marshal.FinalReleaseComObject(workbooks);
Marshal.FinalReleaseComObject(application);
GC.Collect();
如果Excel文件存储在本地机器(客户端计算机)中,则文件会被关闭,但是如果文件存储在服务器中,则不会。日志没有显示抛出异常,这意味着代码 运行 没问题;它只是无法关闭 Excel 文件。在此先感谢您的帮助!
Microsoft.Office.Interop.Word.Application WordApp;
Microsoft.Office.Interop.Word.Document WordDoc;
// coding here
WordDoc.Save();
WordApp.NormalTemplate.Saved = true;
WordDoc.Close(true);
WordApp.Quit();
WordDoc = null;
WordApp = null;
(由于 bugfinder 添加了空赋值)
这会有所帮助,终止服务器上的 excel 进程也可能有所帮助。小心,这会终止所有 excel 进程并关闭所有 excel 文件。
Process[] processes = Process.GetProcessesByName("EXCEL");
Console.WriteLine("{0} Word processes", processes.Length);
foreach (var process in processes)
{
process.Kill();
}
Console.WriteLine("All word processes killed!");
我目前正在开发一个将数据插入 Excel 文件并随后将其关闭的应用程序。 Excel 文件已经存在并存储在服务器的一个目录中。每次我 运行 应用程序都会进入目录,打开 Excel 文件,然后插入数据。
// The codes below are executed after opening the Excel file, inserting data, and saving it.
using xl = Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;
string report = "Report.XLSX";
object obj = Marshal.GetActiveObject("Excel.Application");
xl.Application application = obj as xl.Application;
xl.Workbooks workbooks = application.Workbooks;
foreach (xl.Workbook workbook in workbooks)
{
if (workbook.Name == report)
{
workbook.Close();
}
}
GC.WaitForPendingFinalizers();
if (workbooks != null)
Marshal.FinalReleaseComObject(workbooks);
Marshal.FinalReleaseComObject(application);
GC.Collect();
如果Excel文件存储在本地机器(客户端计算机)中,则文件会被关闭,但是如果文件存储在服务器中,则不会。日志没有显示抛出异常,这意味着代码 运行 没问题;它只是无法关闭 Excel 文件。在此先感谢您的帮助!
Microsoft.Office.Interop.Word.Application WordApp;
Microsoft.Office.Interop.Word.Document WordDoc;
// coding here
WordDoc.Save();
WordApp.NormalTemplate.Saved = true;
WordDoc.Close(true);
WordApp.Quit();
WordDoc = null;
WordApp = null;
(由于 bugfinder 添加了空赋值)
这会有所帮助,终止服务器上的 excel 进程也可能有所帮助。小心,这会终止所有 excel 进程并关闭所有 excel 文件。
Process[] processes = Process.GetProcessesByName("EXCEL");
Console.WriteLine("{0} Word processes", processes.Length);
foreach (var process in processes)
{
process.Kill();
}
Console.WriteLine("All word processes killed!");