C# excel SaveAs file could not be accessed when saving

自古美人都是妖i 提交于 2019-12-11 13:19:42

问题


Attempting to save an excel worksheet programmatically as a unique filename in a loop.

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

This fails with the following error

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.

however when I change the Path string to

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

it resolves.

The goal is to iterate through a loop saving each time as a unique *.csv file. Undetermined amount of .csv files will be generated each time.

a few notes;

writing to the desktop the user account I'm currently doing all the work in. If relevant, I copy a file on the desktop and paste as a different name and work from there.

I feel I might be missing something fairly simple as this kind of issue typically is..


回答1:


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

this is going to work change the tostring. the : is not a character allowed in the path. (look at the 3rd suggestion of the error)



来源:https://stackoverflow.com/questions/31456779/c-sharp-excel-saveas-file-could-not-be-accessed-when-saving

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!