Search code examples
c#excelcom

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


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


Solution

  • 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.