我在 ASP.NET C# 中有一个网页,可以打开一个带有 Microsoft.Office.Interop.Excel 类的 Excel 文件。
Excel 文件具有在 Workbook_BeforeClose 事件上运行的 VBA 代码。使用 Excel 打开和关闭文件时,代码运行良好,并在代码运行后提示保存更改。
但是当用 C# 在网页上做同样的事情时,页面只是毫无意义地加载。调试显示它在 myExcelWorkbook.Close(true); 行停止(等待?)
下面是 C# 代码的样子:
using Excel = Microsoft.Office.Interop.Excel;
public string getExcelInfo(string value1, string value2, string mapPath)
{
Excel.Application myExcelApp;
Excel.Workbooks myExcelWorkbooks;
Excel.Workbook myExcelWorkbook;
object misValue = System.Reflection.Missing.Value;
myExcelApp = new Excel.Application();
myExcelWorkbooks = myExcelApp.Workbooks;
//Copy file to allow simultaneous executions
Random rnd = new Random();
int rand = rnd.Next(1000000);
File.Copy(mapPath+"/App_Data/ConfigAQNX01.xlsm", mapPath+"/App_Data/ConfigAQNX01"+rand.ToString() + ".xlsm");
//Open file, workbook and sheet
String fileName = mapPath+"/App_Data/ConfigAQNX01" + rand.ToString() + ".xlsm";
myExcelWorkbook = myExcelWorkbooks.Open(fileName, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue);
Excel.Worksheet myExcelWorksheet = (Excel.Worksheet)myExcelWorkbook.ActiveSheet;
//insert values
myExcelWorksheet.Cells[3, 2] = value1;
myExcelWorksheet.Cells[6, 2] = value2;
//Save so formulaes are executed
myExcelWorkbook.Save();
myExcelWorksheet = (Excel.Worksheet)myExcelWorkbook.ActiveSheet;
//read value in excel
Excel.Range currentRange = (Excel.Range)myExcelWorksheet.Cells[7, 4];
string Cost_Cad_Unit = currentRange.Value2.ToString();
//Close Excel
GC.Collect();
GC.WaitForPendingFinalizers();
Marshal.ReleaseComObject(currentRange);
Marshal.ReleaseComObject(myExcelWorksheet);
//Set SaveChange to true on close
myExcelWorkbook.Close(true); //This line is where processing takes forever, literraly
Marshal.ReleaseComObject(myExcelWorkbook);
Marshal.ReleaseComObject(myExcelWorkbooks);
myExcelApp.Quit();
Marshal.ReleaseComObject(myExcelApp);
currentRange = null;
myExcelWorksheet = null;
myExcelWorkbook = null;
myExcelWorkbooks = null;
myExcelApp = null;
return Cost_Cad_Unit;
}
是否可以设置选项以使 VBA 代码运行,或者知道是什么导致它挂起的方法?或者 Microsoft.Office.Interop.Excel 是否有限制运行 Workbook_BeforeClose 代码?
谢谢,