Excel.Workbook.SaveAs(...)具有相同的名称文件

Yas*_*ine 11 c# com excel

我正在使用xls文件.如何保存(如果存在)与Windows桌面相同的文件名+"(副本1)".

方法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();
Run Code Online (Sandbox Code Playgroud)

谢谢

Roh*_*hit 15

尝试使用File对象的Exists方法:

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

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

  }  
Run Code Online (Sandbox Code Playgroud)

或者,您也可以覆盖您的Excel文件

   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);
Run Code Online (Sandbox Code Playgroud)

注意:它将覆盖现有的Excel(如果存在)而不询问用户.