在从 c# 向 excel 写入值期间,同时打开 excel 文件它显示 the error that the file is in readonly ,那么我们如何在从 c# 写入流到 Excel 的过程中避免该错误

    //Get all the sheets in the workbook
 mWorkSheets = mWorkBook.Worksheets;
 //Get the allready exists sheet
 mWSheet1 = (Microsoft.Office.Interop.Excel.Worksheet)mWorkSheets.get_Item("Sheet1");
 Microsoft.Office.Interop.Excel.Range range = mWSheet1.UsedRange;

 int colCount = range.Columns.Count;


 int rowCount = range.Rows.Count+1;
 for (int index = 0; index < NoOfRecords; index++)
 {
     for (int j = 0; j < colCount; j++)
     {
         mWSheet1.Cells[(rowCount) + index, j + 1] ="'"+Convert.ToString(ResultsData.Rows[index][j].ToString());
     }
 }


 mWorkBook.SaveAs(path, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal,
 Missing.Value, Missing.Value, Missing.Value, Missing.Value, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive,
 Missing.Value, Missing.Value, Missing.Value,
 Missing.Value, Missing.Value);
mWorkBook.Close(Missing.Value, Missing.Value, Missing.Value);

最佳答案

最简单的方法是将文件另存为不同的文件名,然后在成功保存后删除原始文件。就像打开 MySheet.XLSX 并保存 MySheet_Updated.XLSX

 string newPath = path.Replace(Path.GetFileNameWithoutExtension(path),Path.GetFileNameWithoutExtension(path)+"_Updated)";
 try{
    mWorkBook.SaveAs(newPath,Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal,Missing.Value,Missing.Value,Missing.Value,Missing.Value,Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive,Missing.Value,Missing.Value,Missing.Value,Missing.Value, Missing.Value);
   mWorkBook.Close(Missing.Value, Missing.Value, Missing.Value);
   File.Delete(path);
   File.Move(newPath,path);
   }
 catch(Exception e){
      Console.WriteLine(e.Message+"\n"+e.Source);
 }

关于c# - 如果 excel 文件是打开的,我们如何避免在从 c# 写入 excel 的 writestream 期间只读 excel 文件?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39558285/

10-12 12:48
查看更多