问题描述
publicclassImportExportToExcel{privateSystem.Windows.Forms.OpenFileDialogopenFileDlg=newSystem.Windows.Forms.OpenFileDialog();privateSystem.Windows.Forms.SaveFileDialogsaveFileDlg=newSystem.Windows.Forms.SaveFileDialog();publicImportExportToExcel(){this.openFileDlg.DefaultExt="xls";this.openFileDlg.Filter="Excel文件(*.xls)|*.xls";this.saveFileDlg.DefaultExt="xls";this.saveFileDlg.Filter="Excel文件(*.xls)|*.xls";}publicvoidExportToExcel(DataSetds,stringstrExcelFileName){if(ds.Tables.Count==0||strExcelFileName==""){return;}doExport(ds,strExcelFileName);}publicvoidExportToExcel(DataSetds){if(saveFileDlg.ShowDialog()==System.Windows.Forms.DialogResult.OK)doExport(ds,saveFileDlg.FileName);}privatevoiddoExport(DataSetds,stringstrExcelFileName){Excel.Applicationexcel=newExcel.Application();introwIndex=1;intcolIndex=0;excel.Application.Workbooks.Add(true);System.Data.DataTabletable=ds.Tables[0];foreach(DataColumncolintable.Columns){colIndex++;excel.Cells[1,colIndex]=col.ColumnName;}foreach(DataRowrowintable.Rows){rowIndex++;colIndex=0;foreach(DataColumncolintable.Columns){colIndex++;excel.Cells[rowIndex,colIndex]=row[col.ColumnName].ToString();}}excel.Visible=false;excel.ActiveWorkbook.SaveAs("C:/DocumentsandSettings/Administrator/桌面/"+strExcelFileName+".XLS",Excel.XlFileFormat.xlExcel9795,null,null,false,false,Excel.XlSaveAsAccessMode.xlNoChange,null,null,null,null,null);excel.Quit();excel=null;GC.Collect();//垃圾回收}}上面我是将DataTable里的数据导出到excel的代码,保存得一次后,,再点保存就会提示,要不要替代原来的文件,如果点否或取消就出错了...谁能帮我解决下这问题,先谢谢了.
解决方案
解决方案二:
保存前先删除原有的文件或者换成其它名称
解决方案三:
不知道业务你可以随机让它产生名称
解决方案四:
要是我保存前忘了保存,出错就不好了啊,必竞不是自己用,,是给别人用出错别人又不会.
解决方案五:
excel.AlertBeforeOverwriting=false;
//强制覆盖,不弹出是否存在的对话框
解决方案六:
我也遇到了,现在只有把下面的函数加个捕捉异常privatevoiddoExport(DataSetds,stringstrExcelFileName){Excel.Applicationexcel=newExcel.Application();introwIndex=1;intcolIndex=0;excel.Application.Workbooks.Add(true);System.Data.DataTabletable=ds.Tables[0];foreach(DataColumncolintable.Columns){colIndex++;excel.Cells[1,colIndex]=col.ColumnName;}foreach(DataRowrowintable.Rows){rowIndex++;colIndex=0;foreach(DataColumncolintable.Columns){colIndex++;excel.Cells[rowIndex,colIndex]=row[col.ColumnName].ToString();}}excel.Visible=false;try{excel.ActiveWorkbook.SaveAs("C:/DocumentsandSettings/Administrator/桌面/"+strExcelFileName+".XLS",Excel.XlFileFormat.xlExcel9795,null,null,false,false,Excel.XlSaveAsAccessMode.xlNoChange,null,null,null,null,null);}catch(Exceptionex){}finally{excel.Quit();excel=null;GC.Collect();//垃圾回收}
解决方案七:
5楼的,谢谢啊,,挺有用的.呵