您需要获取对由您的 Web 应用程序打开并仍在运行的 Excel 应用程序的引用。当您拥有此参考资料时,您可以使用 Excel.Interop 并使用所需名称保存/关闭您的工作簿
public bool SaveOpenExcel(string fileName)
{
int iSection = 0, iTries = 0;
Microsoft.Office.Interop.Excel.Application oExcel;
tryAgain:
try
{
iSection = 1; // Attempting GetObject.
oExcel = (Microsoft.Office.Interop.Excel.Application)
System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
iSection = 0; // Resume normal error handling.
oExcel.ActiveWorkbook.SaveAs(@"d:\temp\running.xlsx",
Microsoft.Office.Interop.Excel.XlFileFormat.xlXMLSpreadsheet,
System.Type.Missing, System.Type.Missing, System.Type.Missing,
System.Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing,
System.Type.Missing);
oExcel.Quit();
oExcel = null;
return true;
}
catch (Exception err)
{
if (iSection == 1)
{
//GetObject may have failed because the
//Shell function is asynchronous; enough time has not elapsed
//for GetObject to find the running Office application. Wait
//1/2 seconds and retry the GetObject. If you try 20 times
//and GetObject still fails, assume some other reason
//for GetObject failing and exit the procedure.
iTries++;
if (iTries < 20)
{
System.Threading.Thread.Sleep(500); // Wait 1/2 seconds.
goto tryAgain; //resume code at the GetObject line
}
else
{
Console.WriteLine("GetObject still failing. Process ended.");
return false;
}
}
else
{
//iSection = 0 so use normal error handling:
Console.WriteLine(err.Message);
return false;
}
}
}
此代码示例改编自有关 WinWord 的类似问题的 Microsoft 支持文章。您可以阅读这篇文章以更好地理解这种方法的问题。
我真的建议更改您的 Web 应用程序以完成保存文件的任务。