簡體   English   中英

如果excel文件打開,如何在writestream期間避免excel文件的readonly從c#中脫穎而出?

[英]how can we avoid readonly of the excel file during the writestream to excel from c# , if the excel file is open?

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

最簡單的方法是將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);

    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM