【问题标题】:unable to save excel file using saveAs method in c#无法在c#中使用saveAs方法保存excel文件
【发布时间】:2018-02-15 18:49:35
【问题描述】:

我正在使用 c# 中的 SaveAs 方法保存一个 excel 文件。但它显示如下错误:

附加信息:无法访问该文件。尝试以下方法之一:

• 确保指定的文件夹存在。

• 确保包含该文件的文件夹不是只读的。

• 确保文件名不包含以下任何字符: ? [ ] : |或 *

• 确保文件/路径名包含的字符不超过 218 个。

我的代码是这样的:

string savepath = AppDomain.CurrentDomain.BaseDirectory + @"\Salary Slips\a.xlsx";
xlwbOP.SaveAs(savepath, Excel.XlFileFormat.xlExcel12);

保存路径变量有值 savepath="D:\Application\WindowsFormsApplication1\WindowsFormsApplication1\bin\Debug\Salary Slips\a.xlsx"

并且目录 :"D:\Application\WindowsFormsApplication1\WindowsFormsApplication1\bin\Debug\Salary Slips\" 存在

【问题讨论】:

  • 您是否尝试过像“C:\Temp\a.xlsx”这样的绝对路径?你检查文件是否存在并且没有writeLock?
  • 不确定 BaseDirectory 是否返回尾部反斜杠。永远不要像这样连接路径。使用 System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Salary Slips", "a.xlsx");
  • 文件系统上是否存在"D:\Application\WindowsFormsApplication1\WindowsFormsApplication1\bin\Debug\Salary Slips\"
  • 尝试另存为Excel.XlFileFormat.xlOpenXMLWorkbook 而不是xlExcel12,如下所述:stackoverflow.com/questions/9769703/…
  • 您在使用 Excel 互操作吗?检查您的任务管理器,看看是否有一堆 Excel 实例正在运行。如果是这样,其中一个仍然可以打开您的文件,因此您无法覆盖它。这就是 Excel 互操作是邪恶的原因。我的意思是,这就是 Excel 互操作是邪恶的原因之一。如果有一堆实例正在运行(或者甚至只是一个不应该存在的额外实例),那么您已经找到了问题的解决方案,但现在您必须找到另一个问题的解决方案。

标签: c#


【解决方案1】:

如果我没记错(已经有一段时间了),您应该在尝试保存之前检查以确保文件存在。您可能还希望将其包装在 try-catch 块中,以处理由权限问题或路径不存在引起的异常。

string savepath = AppDomain.CurrentDomain.BaseDirectory + @"\Salary Slips\a.xlsx";
try
{
    if(!File.Exists(savepath))
         xlwbOP.SaveAs(savepath, Excel.XlFileFormat.xlExcel12);
    else
         xlwbOP.Save();
}
catch
{  /*input your exception handling here*/ }

我还推荐verifying that your path doesn't contain invalid characters,然后再尝试使用它来保存。

您可能还想研究使用SaveCopyAs(string) 将副本保存为新文件。

【讨论】:

    【解决方案2】:

    Exporting to .xlsx using Microsoft.Office.Interop.Excel SaveAs Error 中所述,保存为.xlsx 的正确枚举不是Excel.XlFileFormat.xlExcel12,而是Excel.XlFileFormat.xlOpenXMLWorkbook

    因此,这里也合并Missing.Value的正确方法是:

    var missing = System.Reflection.Missing.Value;
    var savepath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Salary Slips", "a.xlsx");
    xlwbOP.SaveAs(savepath, Excel.XlFileFormat.xlOpenXMLWorkbook, missing,
        missing, false, false, missing, missing, true, missing, missing, missing);
    

    感谢 SO 用户 MoonKnight。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-11
      • 1970-01-01
      • 2014-08-30
      • 2022-08-22
      相关资源
      最近更新 更多