Reputation: 151
Using below code, created C# console app which will create Test.xlsx in Files folder.
public class Program
{
public string dailyUpdateFile;
Microsoft.Office.Interop.Excel.Application excel;
Microsoft.Office.Interop.Excel.Workbook worKbooK;
Microsoft.Office.Interop.Excel.Worksheet worKsheeT;
static void Main(string[] args)
{
System.Diagnostics.Debugger.Launch();
Program obj = new Program();
obj.excel = new Microsoft.Office.Interop.Excel.Application();
obj.excel.DisplayAlerts = false;
DirectoryInfo dInfo = Directory.GetParent(Environment.CurrentDirectory);
dInfo = Directory.GetParent(dInfo.FullName);
obj.dailyUpdateFile = dInfo + "\\Files\\Test.xlsx";
if (!File.Exists(obj.dailyUpdateFile))
{
obj.worKbooK = obj.excel.Workbooks.Add(Type.Missing);
obj.worKsheeT = (Microsoft.Office.Interop.Excel.Worksheet)obj.worKbooK.ActiveSheet;
obj.worKsheeT.Name = "TestFile";
obj.worKsheeT.Cells[1, 1] = "Date";
obj.worKsheeT.Cells[1, 2] = "Day";
}
obj.worKbooK.SaveAs(obj.dailyUpdateFile);
obj.excel.Quit();
}
}
Now when application executable is run from Task scheduler, getting below exception:
Exception Info: System.Runtime.InteropServices.COMException
at Microsoft.Office.Interop.Excel._Workbook.SaveAs(System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode, System.Object, System.Object, System.Object, System.Object, System.Object) at Test.Program.Main(System.String[])
The above exception can be catch from Event Viewer.
One thing I want to point out--when the app is run from task scheduler, it is pointing to "C:\Files ", but that it ok, it should create Test.xlsx under that folder.
While debugging I got the below exception:
Upvotes: 0
Views: 989
Reputation: 914
I would rather save the files in shared path with unique filename like random filename with datetime. Only problem i see here is access issues with the user under which the task is running.
Get the path from config and save the files to shared path which will have full permissions to read and write.
It is not recommended to save files in the application server.
Upvotes: 1
Reputation: 109
Is it possible that the permission issue? Please try to grant certain permission to the user in the Security settings, or change another user with enough permission.
Using COM to interoperate with Office without human interaction is not recommeneded. Please check this page for detail. I recommeneded to use NPOI instead, it would be more efficient and reliable for this kind of operations.
Upvotes: 0