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:
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.