且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在不覆盖Excel文件的情况下附加数据

更新时间:2023-09-20 14:52:28

使用 ^ ]方法代替Workbook.SaveAs
Use the Workbook.Save[^] method instead of Workbook.SaveAs


从您发布的代码看来,您在添加工作簿之前已经知道要使用的名称(fName).

因此,在执行任何检查之前,是否存在

From the code that you have posted it seems that you are aware of the name you want to use (fName) prior to Adding your workbook.

Therefore before doing any of that check if it''s there

xlApp = new Excel.Application();
bool newWorkBook = false;

if (File.Exists(fName))
{
  // put code here to open the file
}
else
{
  xlWorkBook = xlApp.Workbooks.Add(misValue);
  newWorkBook = true;
}

xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

// rest of your code

if (newWorkBook)
{
  xlWorkBook.SaveAs(fName);
  xlWorkBook.Close(true, null, null);
}
else
{
  // do normal save here. CHECK SYNTAX OF
  xlWorkBool.Save();  // Dummy statement
}

xlApp.Quit();