Reputation: 113
I have a windows service that calls a batch file to execute a macro in a spreadsheet but when I call the open file method it always comes back with an error. If I run the batch file from the command line it works fine.
The error I get: is Exception has been thrown by the target of an invocation. I'm not sure if I have to configure something to run the batch file from the service.
static void RunExcelMacro(string filePath, string macroName)
{
Workbook workbook = null;
var excelApp = new Application { Visible = false };
try
{
workbook = excelApp.Workbooks.Open(filePath);
excelApp.Run(macroName);
}
catch (Exception ex)
{
Console.WriteLine("Error running macro: " + ex.Message);
}
finally
{
// Close the workbook and release resources
workbook.SaveAs($"{Path.GetDirectoryName(filePath)}\\{Path.GetFileNameWithoutExtension(filePath)}.xlsx",XlFileFormat.xlOpenXMLWorkbook);
workbook.Close(false);
excelApp.Quit();
excelApp.Dispose();
}
}
The service code that runs the batch file is:
var process = new Process()
{
StartInfo = new ProcessStartInfo
{
FileName = "cmd.exe",
Arguments = $"cmd /C \"{fullBatPath}\"",
UseShellExecute = true,
CreateNoWindow = true,
Verb = "runas"
}
};
process.Start();
Upvotes: 0
Views: 11