我目前正在使用Microsoft.Office.Core;
和using Excel = Microsoft.Office.Interop.Excel;
将数据从Windows窗体导出到Excel。
导出文件时,它总是会被覆盖。
有人知道解决方法吗?
xlWorkBook.SaveAs("d:\\csharp-Excel.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWorkSheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWorkBook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
MessageBox.Show("Excel file created , you can find the file d:\\csharp-Excel.xls");
答案 0 :(得分:1)
您可以首先检查所需文件名是否已存在,如果存在,请在其末尾附加一个DateTime。同样,在路径前加上一个“ @”,可以像在资源管理器中一样输入路径(不带双“ \”):
string MyExportFile = "csharp-Excel";
string FullPath = @"d:\";
if (File.Exists(Path.Combine(FullPath, MyExportFile)))
{
MyExportFile += DateTime.Now + ".xls";
FullPath += MyExportFile;
}
xlWorkBook.SaveAs(FullPath,
Excel.XlFileFormat.xlWorkbookNormal,
misValue, misValue, misValue, misValue,
Excel.XlSaveAsAccessMode.xlExclusive,
misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();