Excel.Workbook.SaveAs(...) with a same name file

99,498

try using File object's Exists method:

  if (!System.IO.File.Exists(@"C:\test2.xls"))
  {
   xlWorkBook.SaveAs(@"c:\test2.xls"); 
  }
  else
  {

   xlWorkBook.SaveAs(@"c:\test2(Copy).xls"); 

  }  

Or Alternatively you can overwrite your excel file by

   Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();

  excel.DisplayAlerts = false;

  excelSheePrint.SaveAs(filename, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing, true, false, XlSaveAsAccessMode.xlNoChange, XlSaveConflictResolution.xlLocalSessionChanges, Type.Missing, Type.Missing);

Note: It will overwrite the existing excel (if exist) without asking the user.

Share:
99,498
Yassine
Author by

Yassine

Updated on July 09, 2022

Comments

  • Yassine
    Yassine almost 2 years

    I'm working with xls file. How can I save it (if exist) with the same file name + "(copy 1)" like Windows desktop.

    method saveCommande(...)

            if(!Directory.Exists(System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "EE_Commande_Fournisseur"))
            {
                Directory.CreateDirectory(System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\EE_Commande_Fournisseur");
            }
            xlWorkBook.SaveAs("EE_Commande_Fournisseur\\" + path, Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, true, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
            path = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\EE_Commande_Fournisseur\\" + path;
    
            xlWorkBook.Close(true, misValue, misValue);
            xlApp.Quit();
            this.ReleaseComObject(xlApp,xlWorkBook);
            //sauvergarde dans la base de données
            _newAchatCommande.path = path;
            this._fileName = path;
            contexte.AddToAchatCommande(_newAchatCommande);
            contexte.SaveChanges();
    

    thanks

  • John
    John about 8 years
    What if I want to save data in the same excel file for a number of iterations (without overwriting the existing data) ?