C# excel 保存时无法访问另存为文件

C# excel SaveAs file could not be accessed when saving

正在尝试以编程方式将 excel 工作表保存为循环中的唯一文件名。

    private static DateTime csvtime = DateTime.Now;
    private static string time = csvtime.ToString("HH:mm:ss");
    private static string Path = @"C:\users\User\desktop\MonetaryEntry_"+time+".csv";
    mySheet = (Excel.Worksheet)myBook.Worksheets[1];


mySheet.SaveAs(Path, Microsoft.Office.Interop.Excel.XlFileFormat.xlCSV);

失败并出现以下错误

An unhandled exception of type 'System.Runtime.InteropServices.COMException' occurred in MonetaryEntryFormatting.exe

Additional information: The file could not be accessed. Try one of the following:

• Make sure the specified folder exists.

• Make sure the folder that contains the file is not read-only.

• Make sure the file name does not contain any of the following characters: < > ? [ ] : | or *

• Make sure the file/path name doesn't contain more than 218 characters.

但是当我将路径字符串更改为

private static string path = "@C:\users\user\desktop\MonetaryEntry_.csv";

解决了。

目标是迭代一个循环,每次保存为唯一的 *.csv 文件。每次都会生成数量不确定的 .csv 文件。

一些注意事项;

将我当前正在执行所有工作的用户帐户写入桌面。如果相关,我会在桌面上复制一个文件并以不同的名称粘贴,然后从那里开始工作。

我觉得我可能遗漏了一些相当简单的东西,因为这种问题通常是..

private static DateTime csvtime = DateTime.Now;
private static string time = csvtime.ToString("HH_mm_ss");
private static string Path = @"C:\users\User\desktop\MonetaryEntry_"+time+".csv";
mySheet = (Excel.Worksheet)myBook.Worksheets[1];
mySheet.SaveAs(Path, Microsoft.Office.Interop.Excel.XlFileFormat.xlCSV);

这将有效更改 tostring。 : 不是路径中允许的字符。 (看错误的第三个建议)