WinForm导出文件为Word、Excel、文本文件的方法
好久没有写文章了,下面把自己最近程序中用到的一个小小的导出文件的方法给在家分享一下,欢迎大家来排砖,谢谢~不说废话了,直接上代码:
usingSystem; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Text; usingSystem.Windows.Forms; usingSystem.Threading; usingMicrosoft.Office.Interop.Word; usingSystem.IO; usingMicrosoft.Office.Interop.Excel; usingSun.Winform.Util; namespaceSun.Winform.Files { ///<summary> ///将内容导出为文件类。 ///</summary> ///<remarks> ///作者:SunYujing ///日期:2011-12-18 ///</remarks> publicclassExportFile { ///<summary> ///将字符串存储为word文档格式的文件的方法(多线程)。 ///</summary> ///<paramname="strText">要保存的字符串内容。</param> publicstaticvoidSaveAsWord(stringp_str) { Threadthread=newThread(SaveAsWordFile); thread.SetApartmentState(ApartmentState.STA); thread.Start(p_str); } ///<summary> ///将字符串存储为txt格式的文件的方法(多线程)。 ///</summary> ///<paramname="p_str"></param> publicstaticvoidSaveAsTxt(stringp_str) { Threadthread=newThread(SaveAsTxtFile); thread.SetApartmentState(ApartmentState.STA); thread.Start(p_str); } ///<summary> ///导出数据表数据到Excel(多线程)。 ///</summary> publicstaticvoidSaveAsExcel(System.Data.DataTabledataTable) { if(dataTable==null) { MessageUtil.ShowError("请先指定要导出的数据表"); return; } Threadthread=newThread(SaveAsExcelTableFile); thread.SetApartmentState(ApartmentState.STA); thread.Start(dataTable); } ///<summary> ///导出数据集数据到Excel(多线程)。 ///</summary> publicstaticvoidSaveAsExcel(System.Data.DataSetdataSet) { if(dataSet==null) { MessageUtil.ShowError("请先指定要导出的数据集"); return; } Threadthread=newThread(SaveAsExcelSetFile); thread.SetApartmentState(ApartmentState.STA); thread.Start(dataSet); } ///<summary> ///将字符串存储为word文档格式的文件。 ///</summary> ///<paramname="strtext">要保存的字符串内容。</param> privatestaticvoidSaveAsWordFile(objectstrtext) { SaveFileDialogsfd=newSaveFileDialog(); sfd.Title="请选择文件存放路径"; sfd.FileName="导出数据"; sfd.Filter="Word文档(*.doc)|*.doc"; if(sfd.ShowDialog()!=DialogResult.OK) { return; } stringFileName=sfd.FileName.ToLower(); if(!FileName.Contains(".doc")) { FileName+=".doc"; } if(FileName.Substring(FileName.LastIndexOf(Path.DirectorySeparatorChar)).Length<=5) { MessageUtil.ShowThreadMessage("文件保存失败,文件名不能为空!"); return; } try { DateTimestart=DateTime.Now; MessageUtil.ShowThreadMessage("正在保存文件,请稍候..."); Microsoft.Office.Interop.Word.ApplicationClassword=newMicrosoft.Office.Interop.Word.ApplicationClass(); Microsoft.Office.Interop.Word._Documentdoc; objectnothing=System.Reflection.Missing.Value; doc=word.Documents.Add(refnothing,refnothing,refnothing,refnothing); doc.Paragraphs.Last.Range.Text=strtext.ToString(); objectmyfileName=FileName; //将WordDoc文档对象的内容保存为doc文档 doc.SaveAs(refmyfileName,refnothing,refnothing,refnothing,refnothing,refnothing,refnothing,refnothing,refnothing,refnothing,refnothing,refnothing,refnothing,refnothing,refnothing,refnothing); //关闭WordDoc文档对象 doc.Close(refnothing,refnothing,refnothing); //关闭WordApp组件对象 word.Quit(refnothing,refnothing,refnothing); GC.Collect(); DateTimeend=DateTime.Now; TimeSpants=end-start; MessageUtil.ShowMessage("文件保存成功,用时"+ts.ToString()); } catch(System.Exceptionex) { MessageUtil.ShowError(ex.Message); } } ///<summary> ///将字符串存储为txt文档格式的文件。 ///</summary> ///<paramname="strtext">要保存的字符串内容。</param> privatestaticvoidSaveAsTxtFile(objectstrtext) { SaveFileDialogsfd=newSaveFileDialog(); sfd.Title="请选择文件存放路径"; sfd.FileName="导出数据"; sfd.Filter="文本文档(*.txt)|*.txt"; if(sfd.ShowDialog()!=DialogResult.OK) { return; } stringFileName=sfd.FileName.ToLower(); if(!FileName.Contains(".txt")) { FileName+=".txt"; } if(FileName.Substring(FileName.LastIndexOf(Path.DirectorySeparatorChar)).Length<=5) { MessageUtil.ShowThreadMessage("文件保存失败,文件名不能为空!"); return; } try { DateTimestart=DateTime.Now; StreamWritersw=newStreamWriter(FileName,false); sw.Write(strtext.ToString()); sw.Flush(); sw.Close(); DateTimeend=DateTime.Now; TimeSpants=end-start; MessageUtil.ShowMessage("文件保存成功,用时"+ts.ToString()); } catch(Exceptionex) { MessageUtil.ShowError(ex.Message); } } ///<summary> ///将数据存储为Excel文件。 ///</summary> ///<paramname="p_dt">要保存的数据表。</param> privatestaticvoidSaveAsExcelTableFile(objectp_dt) { System.Data.DataTabledt=(System.Data.DataTable)p_dt; if(dt.Rows.Count==0) { MessageUtil.ShowError("没有可保存的数据"); return; } SaveFileDialogsfd=newSaveFileDialog(); sfd.Title="请选择文件存放路径"; sfd.FileName="导出数据"; sfd.Filter="Excel文档(*.xls)|*.xls"; if(sfd.ShowDialog()!=DialogResult.OK) { return; } stringFileName=sfd.FileName.ToLower(); if(!FileName.Contains(".xls")) { FileName+=".xls"; } if(FileName.Substring(FileName.LastIndexOf(Path.DirectorySeparatorChar)).Length<=5) { MessageUtil.ShowThreadMessage("文件保存失败,文件名不能为空!"); return; } if(sfd.FileName!="") { Microsoft.Office.Interop.Excel.ApplicationexcelApp=newMicrosoft.Office.Interop.Excel.Application(); if(excelApp==null) { MessageBox.Show("无法创建Excel对象,可能您的机器未安装Excel"); return; } else { MessageUtil.ShowThreadMessage("正在导出数据,请稍候..."); DateTimestart=DateTime.Now; Microsoft.Office.Interop.Excel.Workbooksworkbooks=excelApp.Workbooks; Microsoft.Office.Interop.Excel.Workbookworkbook=workbooks.Add(XlWBATemplate.xlWBATWorksheet); Microsoft.Office.Interop.Excel.Worksheetworksheet=(Worksheet)workbook.Worksheets[1]; for(intcol=1;col<=dt.Columns.Count;col++) { worksheet.Cells[1,col]=dt.Columns[col-1].Caption.ToString(); } for(inti=0;i<dt.Rows.Count;i++) { for(intj=0;j<dt.Columns.Count;j++) { worksheet.Cells[i+2,j+1]=dt.Rows[i][j].ToString(); } } workbook.Saved=true; workbook.SaveCopyAs(sfd.FileName); //释放资源 System.Runtime.InteropServices.Marshal.ReleaseComObject(worksheet); worksheet=null; System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook); workbook=null; workbooks.Close(); System.Runtime.InteropServices.Marshal.ReleaseComObject(workbooks); workbooks=null; excelApp.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp); excelApp=null; //使用垃圾回收可以关闭EXCEL.EXE进程 GC.Collect(); DateTimeend=DateTime.Now; intiTimeSpan=(end.Minute-start.Minute)*60+(end.Second-start.Second); MessageUtil.ShowMessage("数据导出完毕,用时"+iTimeSpan.ToString()+"秒"); } } } ///<summary> ///将数据集存储为Excel文件。 ///</summary> ///<paramname="p_ds">要导出的数据集。</param> privatestaticvoidSaveAsExcelSetFile(objectp_ds) { System.Data.DataSetds=(System.Data.DataSet)p_ds; if(ds==null||ds.Tables.Count==0) { MessageUtil.ShowError("没有可保存的数据"); return; } SaveFileDialogsfd=newSaveFileDialog(); sfd.Title="请选择文件存放路径"; sfd.FileName="导出数据"; sfd.Filter="Excel文档(*.xls)|*.xls"; if(sfd.ShowDialog()!=DialogResult.OK) { return; } stringFileName=sfd.FileName.ToLower(); if(!FileName.Contains(".xls")) { FileName+=".xls"; } if(FileName.Substring(FileName.LastIndexOf(Path.DirectorySeparatorChar)).Length<=5) { MessageUtil.ShowThreadMessage("文件保存失败,文件名不能为空!"); return; } if(sfd.FileName!="") { Microsoft.Office.Interop.Excel.ApplicationexcelApp=newMicrosoft.Office.Interop.Excel.Application(); if(excelApp==null) { MessageBox.Show("无法创建Excel对象,可能您的机器未安装Excel"); return; } else { MessageUtil.ShowThreadMessage("正在导出数据,请稍候..."); DateTimestart=DateTime.Now; Microsoft.Office.Interop.Excel.Workbooksworkbooks=excelApp.Workbooks; Microsoft.Office.Interop.Excel.Workbookworkbook=workbooks.Add(XlWBATemplate.xlWBATWorksheet); Microsoft.Office.Interop.Excel.Worksheetworksheet=null; objectobjMissing=System.Reflection.Missing.Value; for(intm=0;m<ds.Tables.Count;m++) { System.Data.DataTabledt=ds.Tables[m]; worksheet=(Worksheet)workbook.ActiveSheet; worksheet.Name=dt.TableName; for(intcol=1;col<=dt.Columns.Count;col++) { worksheet.Cells[1,col]=dt.Columns[col-1].Caption.ToString(); } for(inti=1;i<=dt.Rows.Count;i++) { for(intj=1;j<=dt.Columns.Count;j++) { worksheet.Cells[i+1,j]=dt.Rows[i-1][j-1].ToString(); } } if(m<ds.Tables.Count-1) { workbook.Sheets.Add(objMissing,objMissing,1,XlSheetType.xlWorksheet); } } workbook.Saved=true; workbook.SaveCopyAs(sfd.FileName); //释放资源 System.Runtime.InteropServices.Marshal.ReleaseComObject(worksheet); worksheet=null; System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook); workbook=null; workbooks.Close(); System.Runtime.InteropServices.Marshal.ReleaseComObject(workbooks); workbooks=null; excelApp.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp); excelApp=null; GC.Collect(); DateTimeend=DateTime.Now; intiTimeSapn=(end.Minute-start.Minute)*60+(end.Second-start.Second); MessageUtil.ShowMessage("数据导出完毕,用时"+(iTimeSapn/60).ToString()+"分"+(iTimeSapn%60).ToString()+"秒"); } } } } }