当从任务计划程序运行C#可执行文件时,无法创建和保存Excel文件

问题描述 投票:0回答:2

使用下面的代码,创建了C#控制台应用程序,它将在Files文件夹中创建Test.xlsx。

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();
    }
}

现在从任务计划程序运行应用程序可执行文件时,出现以下异常:

异常信息:System.Runtime.InteropServices.COMException在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)在Test.Program.Main(System.String [])

以上异常可以从事件查看器中捕获。

以为我很想找到解决方法,但一天之内无法解决。

[有人想指出,当从任务计划程序运行应用程序时,它指向“ C:\ Files”,但没关系,它应该在该文件夹下创建Test.xlsx。

虽然调试得到以下异常

enter image description here

对此提供帮助。

c# task taskscheduler windows-task-scheduler
2个回答
0
投票

我宁愿使用唯一的文件名(例如带日期时间的随机文件名)将文件保存在共享路径中。我在这里看到的唯一问题是正在运行任务的用户的访问问题。

从配置获取路径并将文件保存到共享路径,该路径将具有读取和写入的完整权限。

不建议将文件保存在应用程序服务器中。

谢谢基兰


0
投票

是否可能出现权限问题?请尝试在“安全性”设置中向该用户授予某些权限,或者更改具有足够权限的其他用户。

不建议使用COM与Office进行互操作而不进行人工干预。请检查此page以获取详细信息。我建议改用NPOI,这样操作起来会更加有效和可靠。

© www.soinside.com 2019 - 2024. All rights reserved.