【发布时间】:2021-02-07 23:54:11
【问题描述】:
我正面临一个特殊的问题,我一开始并没有想到这是一个难以解决的错误。
我为 WPF 应用程序创建了一个 Excel 按钮,单击该按钮时会执行以下操作:
方法一
//using the OfficeOpenXmland EPPlus packages
public void CreateCopyReportServerNameDB(string sourceFile)
{
ExcelPackage.LicenseContext = OfficeOpenXml.LicenseContext.NonCommercial;
FileInfo existingFile = new FileInfo(sourceFile);
using (ExcelPackage package = new ExcelPackage(existingFile))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets["Cover"];
worksheet.Cells[7, 4].Value = ConnectionDetailsList[0].ToString();
worksheet.Cells[8, 4].Value = ConnectionDetailsList[1].ToString();
package.SaveAs(new FileInfo($@"{path}{"file_Report.xlsm"}"));
package.Dispose();
}
}
方法二:执行宏
public int ExecuteExcelMacro(string sourceFile) //string sourceFile //String.Format("{0}DQTool_Report.xlsm", path)
{
var destinationFile = @"file_Report";
Excel.Application ExcelApp = new Excel.Application
{
DisplayAlerts = false,
Visible = false
};
Excel.Workbook ExcelWorkBook;
ExcelWorkBook = ExcelApp.Workbooks.Open(sourceFile);
string macro = "ThisWorkbook.Run_Code";
try
{
ExcelApp.Run(macro);
Debug.WriteLine("Macro: " + macro + " executed successfully");
ExcelApp.DisplayAlerts = false;
ExcelApp.Visible = false;
ExcelWorkBook.SaveAs($@"{path}{destinationFile}", Excel.XlFileFormat.xlOpenXMLWorkbook, Type.Missing);
GC.Collect();
GC.WaitForPendingFinalizers();
ExcelWorkBook.Close(0);
if (ExcelWorkBook != null) { Marshal.ReleaseComObject(ExcelWorkBook); }
ExcelApp.Quit();
if (ExcelApp != null) { Marshal.ReleaseComObject(ExcelApp); }
return 1;
}
catch (Exception ex)
{
Debug.WriteLine("Macro not run");
//I repeat the Garbage Collector because if the macro fails to execute the excel workbooks remains open.
GC.Collect();
GC.WaitForPendingFinalizers();
ExcelWorkBook.Close(0);
if (ExcelWorkBook != null) { Marshal.ReleaseComObject(ExcelWorkBook); }
ExcelApp.Quit();
if (ExcelApp != null) { Marshal.ReleaseComObject(ExcelApp); }
MessageBox.Show(ex.ToString());
return 0;
}
}
然后我将方法 1 和方法 2 组合在一个按钮单击下,如下所示:
public string path = AppDomain.CurrentDomain.BaseDirectory; //The folder where the .exe file is executed.
private void PreviewExcelReportButton_Click(object sender, RoutedEventArgs e)
{
try
{
Mouse.OverrideCursor = Cursors.Wait;
//Method 1: Create copy of standard report file
CreateCopyReportServerNameDB($@"{path}file.xlsm");
//Method 2: Run macro
if (ExecuteExcelMacro($@"{path}file_Report.xlsm") == 0)
return;
Debug.WriteLine("End");
}
catch (Exception)
{
MessageBox.Show(ex.ToString(), "Error", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
finally
{
Mouse.OverrideCursor = null;
}
}
即使在我调试应用程序时按钮运行完全成功[调试器在桌面文件夹中运行(也显示在下图中)],但当我移动应用程序文件夹时它会失败将所有 dll 文件和 .exe 文件复制到 C:\ 中的文件夹位置。当特定按钮无法执行excel文件的宏时,会产生如下错误:
提前感谢您对此事的任何评论或想法,我很高兴与您分享任何其他信息。
问候。
【问题讨论】: