我使用 .NET 互操作创建了 excel 工作簿。通过我的 C# 代码成功创建了 excel 工作簿。当用户在 excel 中进行任何更改时,我想做一些事情。我已经使用了该ExcelWorkSheet.Change
事件。但是这个事件没有触发。这是我的代码-
using Excel = Microsoft.Office.Interop.Excel;
public class xxx
{
static Excel.Application xlApp;
static Excel.Workbook xlWorkBook;
static Excel.Worksheet xlWorkSheet;
static Excel.Worksheet xlWorkSheet1;
static Excel.DocEvents_ChangeEventHandler EventDel_CellsChange;
public static void ExportToExcel()
{
xlApp = new Excel.ApplicationClass();
object misValue = System.Reflection.Missing.Value;
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlWorkSheet1 = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(2);
---------------- data is dumped to the excel here----------------
((Microsoft.Office.Interop.Excel._Worksheet)xlWorkSheet).Activate();
xlApp.EnableEvents = true;
EventDel_CellsChange = new Excel.DocEvents_ChangeEventHandler(Worksheet_Change);
xlWorkSheet.Change += EventDel_CellsChange;
xlWorkBook.SaveAs("D:\\Test.xlsx", Excel.XlFileFormat.xlWorkbookDefault, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlShared, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
releaseObject(xlWorkSheet1);
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "application/vnd.ms-excel";
response.AddHeader("Content-Disposition", "attachment; filename=Test.xlsx;");
response.TransmitFile(("D:\\Test.xlsx");
response.Flush();
response.End();
}
public static void Worksheet_Change(Excel.Range Target)
{
try
{
xlApp.EnableEvents = false;
Excel.Range range = xlWorkSheet.get_Range("Y2");
range.Formula = "=A2";
}
catch (Exception ex)
{
}
finally
{
xlApp.EnableEvents = true;
}
}
}
当用户进行一些更改时,Excel 文件中不会反映任何更改。请帮帮我。提前致谢