导出excel文件,旧文件内容不被覆盖
在一个winform中,写入以下代码导出一个excel文件,生成的文件名为tt1.xls,其sheet1.xls的表名改为"表1"。但是,在第二次保存excel文件后,生成另一个文件tt2.xls。但是tt1.xls的内容却被tt2.xls的内容覆盖了,求问原因及解决办法。如何能够在生成新的excel文件的同时,保持旧文件不被改变程序代码:
private void SaveTableToExcel(string filepath) { Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.ApplicationClass(); try { app.Visible = false; Excel.Workbook wBook = app.Application.Workbooks.Add(true); Excel.Worksheet wSheet = wBook.Worksheets[1] as Excel.Worksheet; wSheet.Name = "表1"; int rowNum = connsqlClass.hisListData.Count; int columnNum = 6; object[,] dataArray = new object[rowNum + 1, columnNum]; //将dataTable的标题导入到EXECL的标题(第一行) dataArray[0, 0] = "时间"; dataArray[0, 1] = "编号"; dataArray[0, 2] = "名称"; dataArray[0, 3] = "位置"; dataArray[0, 4] = "类型"; dataArray[0, 5] = "值"; for (int i = 0; i < rowNum; i++) { dataArray[i + 1, 0] = connsqlClass.hisListTime[i]; dataArray[i + 1, 1] = No; dataArray[i + 1, 2] = Name; dataArray[i + 1, 3] = Place; dataArray[i + 1, 4] = Type; dataArray[i + 1, 5] = connsqlClass.hisListData[i]; } wSheet.get_Range("A2", wSheet.Cells[rowNum + 1, columnNum]).Value2 = dataArray; app.DisplayAlerts = false; app.AlertBeforeOverwriting = false; //保存工作簿 wBook.Save(); //保存excel文件 app.Save(filepath); app.SaveWorkspace(filepath); app.Quit(); app = null; } catch (Exception err) { MessageBox.Show("导出Excel出错!错误原因:" + err.Message, "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information); } finally { } }