如果excel文件打开,我们如何避免在writestream期间只读excel文件从excel中脱颖而出?

在从c#写入excel的过程中,同时excel文件打开,它显示the error that the file is in readonly ,所以我们如何能够避免在从c#写入stream中的错误到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); 

最简单的方法是SAVEAS到不同的文件名,然后在成功保存时删除原始文件。 像打开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); } 
  public System.Data.DataTable CorruptedExcel(string path, string savedFile) { try { Missing missing = Missing.Value; Excel.Application excel = new Excel.Application(); Microsoft.Office.Interop.Excel.Workbook workbook = excel.Workbooks.Open(path, CorruptLoad: Microsoft.Office.Interop.Excel.XlCorruptLoad.xlRepairFile); var connectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + path + ";Extended Properties=\"Excel 8.0;HDR=YES;TypeGuessRows=0;ImportMixedTypes=Text\""; //var connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=\"Excel 12.0;IMEX=1;HDR=NO;TypeGuessRows=0;ImportMixedTypes=Text\""; ; using (var conn = new OleDbConnection(connectionString)) { conn.Open(); var sheets = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" }); using (var cmd = conn.CreateCommand()) { cmd.CommandText = "SELECT * FROM [" + sheets.Rows[0]["TABLE_NAME"].ToString() + "] "; var adapter = new OleDbDataAdapter(cmd); adapter.Fill(dt); } } return dt; } catch (Exception e) { throw new Exception("ReadingExcel: Excel file could not be read! Check filepath.\n" + e.Message + e.StackTrace); } }