【问题标题】:C# saving excel file with specific filename using `[ ]` does not workC#使用`[]`保存具有特定文件名的excel文件不起作用
【发布时间】:2020-03-13 15:36:23
【问题描述】:

我正在尝试保存具有特定路径和文件名的 Excel 工作簿,文件扩展名为 .xlsx

这是完整的错误,当我点击按钮保存时:

$exception {"无法访问该文件。请尝试以下方法之一:\n\n• 确保指定的文件夹存在。\n• 确保包含该文件的文件夹不是只读的。\ n• 确保文件名和文件夹路径不包含以下任何字符: ? [ ] : | 或 *\n• 确保文件名和文件夹路径不包含超过 218 个字符。"} System.Runtime .InteropServices.COMException

我看到它说 - do not contain any of the following characters: < > ? [ ] : |

代码:

//Path
string result = "C:\\Users\\LV98\\Desktop\\Test C#\\";

//Save Path
public string TheValue
{
    get { return $"{result}{Path.GetFileNameWithoutExtension(f8.filePath)} [{DateTime.Now.ToString("ddMyyyyHHmmss")}].xlsx"; }
}

//Button
private void button1_Click(object sender, EventArgs e)
{
    //Excel Application
    excelApp = new Excel.Application();
    //Excel Workbooks
    workbooks = excelApp.Workbooks;
    //Excel Workbook
    target = workbooks.Add(f8.filePath);
    //Excel all sheets from Workbook
    Excel.Sheets sheets = target.Worksheets;
    //Get specific sheet name
    Excel.Worksheet workingSheet = (Excel.Worksheet)sheets.get_Item(value);

    var newbook = excelApp.Workbooks.Add(1);

    workingSheet.Copy(newbook.Sheets[1]);

    newbook.SaveAs(TheValue); // ----------------------------------------------------- SAVE VALUE HERE
    newbook.Close();

    target.Close();
    excelApp.Quit();
    killExcel();

    this.Close()    
}

详情:

我的“另存为”文件路径中显然有 []

但我可以手动创建一个文件,并使用[] 命名它没有问题..

这是TheValue的输出:

关注:

为什么这不让我使用[]

【问题讨论】:

  • \ / : * ? " < > | 这些是不可能的字符。
  • @TheGridLock 和 OP 文件名不包含其中任何一个。 OP 询问[ ]
  • 我认为他要保存一个文件并且路径超过255个字符!所以他收到了这个错误。
  • @TheGridLock 没有,路径贴出来了,只有56个。
  • 别让我猜。只有他知道到底发生了什么!

标签: c# excel


【解决方案1】:

这是一般的 Excel 限制,与 COM 无关,如果您尝试从 Excel 中保存名称中包含方括号的文件,您将收到完全相同的消息。我想原因是在 Excel 中,您可以使用以下公式在公式中引用另一个工作簿文件:

='E:\Temp\[Test.xlsx]Sheet1'!$A$1

我不相信有任何方法可以转义括号字符,因此包括这些字符将无法从另一个工作簿中引用它。我建议不要尝试解决它,而是坚持使用允许的括号,但如果有人坚持以这种方式命名文件,您可以执行以下操作:

public string TheValue
{
   get { return $"{result}{Path.GetFileNameWithoutExtension(f8.filePath)} ({DateTime.Now.ToString("ddMyyyyHHmmss")}).xlsx"; }
}
File.Move(TheValue, TheValue.Replace("(","[").Replace(")","]"));

这是假设文件名不可能已经包含括号,如果可以的话,您可以最初将其保存为 Excel 中的唯一文件名,然后使用现有的 TheValue 作为 File.Move 的最终目标。

【讨论】:

    猜你喜欢
    • 2022-10-14
    • 1970-01-01
    • 2021-09-08
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多