
本文实例讲述了C#实现DataSet内数据转化为Excel和Word文件的通用类。分享给大家供大家参考,具体如下:
前不久因为项目的需要写的一个C#把DataSet内数据转化为Excel和Word文件的通用类,这些关于Excel、Word的导出方法,基本可以实现日常须要,其中有些方法可以把数据导出后 生成Xml格式,再导入数据库!有些屏蔽内容没有去掉,保留下来方便学习参考用之。 最后请引用Office相应COM组件,导出Excel对象的一个方法要调用其中的一些方法和属性。
using System;using System.Collections;using System.ComponentModel;using System.Data;using System.Web;using System.Web.SessionState;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.HTMLControls;using System.IO;using System.windows.Forms;using Microsoft.Office.Interop.Excel;using Microsoft.Office.Interop.Word;using Microsoft.Office.Core;using OWC=Microsoft.Office.Interop;using System.Reflection;using System.Text;namespace CaOnline.ZWDB.DFObject{ /// <summary> /// Exportfiles 的摘要说明。 /// 作用:把DataSet数据集内数据转化为Excel、Word文件 /// 描述:这些关于Excel、Word的导出方法,基本可以实现日常须要,其中有些方法可以把数据导出后 /// 生成Xml格式,再导入数据库!有些屏蔽内容没有去掉,保留下来方便学习参考用之。 /// 备注:请引用Office相应COM组件,导出Excel对象的一个方法要调用其中的一些方法和属性。 /// </summary> public class Exportfiles { /// <summary> /// /// </summary> /// #region //构造函数 public Exportfiles() { // // Todo: 在此处添加构造函数逻辑 // } #endregion /// <summary> /// 调用Excel.dll导出Excel文件 /// </summary> /// <param name="ds"></param> /// #region // 调用Excel.dll导出Excel文件 /// <summary> /// /// </summary> /// <param name="ds">DataSet数据庥</param> /// <param name="Duser">登录用户(如session["username"].Tostring())可为null或空</param> /// <param name="Titlename">添加一个报表标题</param> /// <param name="filepath">指定文件在服务器上的存放地址(如:Server.MapPath("."))可为null或空</param> /// /// 为什么在这里设置个filepath? /// 原因如下:filepath接收的内容是Server.MapPath(".")这个参数值,这个值在这本类中对 /// System.Web.httpServerUtility HServer=new System.Web.httpServerUtility()的引用出错,因为没有继承Page类 /// 所以只能以传值的形式调用了,你有好的办法可以修改,那就再好不过了! public voID DataSetToExcel(DataSet ds,string Duser,string Titlename,string filepath) { //Microsoft.Office.Interop.Owc11() appowc=new Microsoft.Office.Interop.Owc11(); OWC.Owc11.SpreadsheetClass xlsheet=new Microsoft.Office.Interop.Owc11.SpreadsheetClass(); #region //屏蔽内容 ///本来想用下面的这个办法实现的,可在IIS中必须设置相关的权限 ///所以就放弃了,把代码设置为屏蔽内容,供学习参考! ///// Microsoft.Office.Interop.Excel.Application app=new Microsoft.Office.Interop.Excel.Application();//// if(app==null)// {// throw new Exception("系统调用错误(Excel.dll)");// }// app.Application.Workbooks.Add(true);// WorkbookClass oBook=new WorkbookClass();// WorksheetClass oSheet=new WorksheetClass();//// //定义表对象与行对象,同时用DataSet对其值进行初始化// System.Data.Datatable dt=ds.tables[0];// oSheet.get_Range(app.Cells[1,1],app.Cells[10,15]).HorizontalAlignment=OWC.Owc11.XlHAlign.xlHAlignCenter;// DaTarow[] myRow=dt.Select();// int i=0;// int cl=dt.Columns.Count;// //取得数据表各列标题// for(i=0;i<cl;i++)// {// app.Cells[1,i+1]=dt.Columns[i].Caption.ToString();// //app.Cells.AddComment(dt.Columns[i].Caption.ToString());// //oSheet.Cells.AddComment(dt.Columns[i].Caption.ToString());// //app.Cells=dt.Columns[i].Caption.ToString();// //oSheet.get_Range(app.Cells,app.Cells).HorizontalAlignment=// //app.Cells.AddComment=dt.Columns[i].ToString();// //oSheet.get_Range(app.Cells,app.Cells).HorizontalAlignment=// } #endregion //定义表对象与行对象,同时用DataSet对其值进行初始化 System.Data.Datatable dt=ds.tables[0]; DaTarow[] myRow=dt.Select(); int i=0; int col=1; int colday=col+1; int colsecond=colday+1; int colnumber=colsecond+1; int cl=dt.Columns.Count; string userfile=null; //合并单元格 xlsheet.get_Range(xlsheet.Cells[col,col],xlsheet.Cells[col,cl]).set_MergeCells(true); //添加标题名称 if(Titlename=="" || Titlename==null) xlsheet.ActiveSheet.Cells[col,col]="添加标题处(高级报表)"; else xlsheet.ActiveSheet.Cells[col,col]=Titlename.Trim(); //判断传值user是否为空 if(Duser=="" || Duser==null) userfile="DFSOFT"; else userfile=Duser; //设置标题大小 xlsheet.get_Range(xlsheet.Cells[col,cl]).Font.set_Size(13); //加粗标题 xlsheet.get_Range(xlsheet.Cells[col,cl]).Font.set_Bold(true); xlsheet.get_Range(xlsheet.Cells[colsecond,xlsheet.Cells[colsecond,cl]).Font.set_Bold(true); //设置标题水平居中 xlsheet.get_Range(xlsheet.Cells,xlsheet.Cells).set_HorizontalAlignment(OWC.Owc11.XlHAlign.xlHAlignCenter); //设置单元格宽度 //xlsheet.get_Range(xlsheet.Cells,xlsheet.Cells).set_ColumnWIDth(9); xlsheet.get_Range(xlsheet.Cells[colday,xlsheet.Cells[colday,cl]).set_MergeCells(true); xlsheet.ActiveSheet.Cells[colday,col]="日期:"+DateTime.Now.Year.ToString()+"年"+DateTime.Now.Month.ToString()+"月"+DateTime.Now.Day.ToString()+"日 "; xlsheet.get_Range(xlsheet.Cells[colday,cl]).set_HorizontalAlignment(OWC.Owc11.XlHAlign.xlHAlignRight); //取得数据表各列标题,各标题之间以\t分割,最后一个列标题后加回车符 for(i=0;i<cl;i++) { xlsheet.ActiveSheet.Cells[colsecond,i+1]=dt.Columns[i].Caption.ToString(); } //逐行处理数据 foreach(DaTarow row in myRow) { //当前数据写入 for(i=0;i<cl;i++) { xlsheet.ActiveSheet.Cells[colnumber,i+1]=row[i].ToString().Trim(); } colnumber++; } //设置边框线 xlsheet.get_Range(xlsheet.Cells[colsecond,xlsheet.Cells[colnumber-1,cl]).borders.set_linestyle(OWC.Owc11.Xllinestyle.xlContinuous); try { //xlsheet.get_Range(xlsheet.Cells[2,xlsheet.Cells[8,15]).set_NumberFormat("¥#,##0.00"); // System.Web.httpServerUtility HServer=new System.Web.httpServerUtility(); //HServer.MapPath(".")+"//testowc.xls"; xlsheet.Export(filepath+"//exportfiles//~$"+userfile+".xls",OWC.Owc11.SheetExportActionEnum.ssExportActionNone,OWC.Owc11.SheetExportFormat.ssExportXMLSpreadsheet); } catch(Exception e) { throw new Exception("系统调用错误或有打开的Excel文件!"+e); } //Web页面定义 httpResponse resp; resp=httpContext.Current.Response; resp.ContentEnCoding=System.Text.EnCoding.GetEnCoding("GB2312"); resp.Appendheader("Content-disposition","attachment;filename="+userfile+".xls"); resp.ContentType="application/ms-excel"; string path=filepath+"//exportfiles//~$"+userfile+".xls"; System.IO.fileInfo file = new fileInfo(path); resp.Clear(); resp.Addheader("content-length",file.Length.ToString()); resp.Writefile(file.Fullname); resp.End(); } #endregion /// <summary> /// 导出Excel文件类 /// </summary> /// <param name="ds"></param> /// <param name="filename"></param> /// #region //导出Excel文件类 public voID DataSetToExcel(DataSet ds,string filename) { try { //Web页面定义 //System.Web.UI.Page mypage=new System.Web.UI.Page(); httpResponse resp; resp=httpContext.Current.Response; resp.ContentEnCoding=System.Text.EnCoding.GetEnCoding("GB2312"); resp.Appendheader("Content-disposition","attachment;filename="+filename+".xls"); resp.ContentType="application/ms-excel"; //变量定义 string colheaders=null; string Is_item=null; //显示格式定义//////////////// //文件流 *** 作定义 // fileStream fs=new fileStream(filename,fileMode.Create,fileAccess.Write); //StreamWriter sw=new StreamWriter(fs,System.Text.EnCoding.GetEnCoding("GB2312")); StringWriter sfw=new StringWriter(); //定义表对象与行对象,同时用DataSet对其值进行初始化 System.Data.Datatable dt=ds.tables[0]; DaTarow[] myRow=dt.Select(); int i=0; int cl=dt.Columns.Count; //取得数据表各列标题,各标题之间以\t分割,最后一个列标题后加回车符 for(i=0;i<cl;i++) { //if(i==(cl-1)) //最后一列,加\n // colheaders+=dt.Columns[i].Caption.ToString(); //else colheaders+=dt.Columns[i].Caption.ToString()+"\t"; } sfw.Writeline(colheaders); //sw.Writeline(colheaders); //逐行处理数据 foreach(DaTarow row in myRow) { //当前数据写入 for(i=0;i<cl;i++) { //if(i==(cl-1)) // Is_item+=row[i].ToString()+"\n"; //else Is_item+=row[i].ToString()+"\t"; } sfw.Writeline(Is_item); //sw.Writeline(Is_item); Is_item=null; } resp.Write(sfw); //resp.Clear(); resp.End(); } catch(Exception e) { throw e; } } #endregion /// <summary> /// 数据集转换,即把DataSet转换为Excel对象 /// </summary> /// <param name="ds"></param> /// <param name="filename"></param> /// <param name="Titlename"></param> /// #region //运用HTML+CSS生成Excel public voID DataSetToExcel(DataSet ds,String filename,string Titlename) { string Exportfilename=null; if(filename==null || filename=="") Exportfilename="DFSOFT"; else Exportfilename=filename; if(Titlename=="" || Titlename==null) Titlename="添加标题处(高级报表)"; //定义表对象与行对象,同时用DataSet对其值进行初始化 System.Data.Datatable dt=ds.tables[0]; DaTarow[] myRow=dt.Select(); int i=0; int cl=dt.Columns.Count; //Web页面定义 httpResponse resp; resp=httpContext.Current.Response; resp.Clear(); resp.ContentEnCoding=System.Text.EnCoding.GetEnCoding("utf-8"); resp.Appendheader("Content-disposition","attachment;filename="+Exportfilename+".xls"); resp.ContentType="application/vnd.ms-excel"; string BeginTab="<table border='0' cellpadding='0' cellspacing='0' style='border-right:#000000 0.1pt solID;border-top:#000000 0.1pt solID;'>"; string EndTab="</table>"; string fileIO=null; string MainIO=null; string TitleTab="<tr><td colspan='"+cl+"' style='Font-size:30px;' align='center'><b>"+Titlename+"</b></td></tr><tr><td colspan='"+cl+"' align='right' style='Font-size:15px;'>"+DateTime.Now.Year.ToString()+"年"+DateTime.Now.Month.ToString()+"月"+DateTime.Now.Day.ToString()+"日 </td></tr>"; string BeginTr="<tr>"; string EndTr="</tr>"; for(i=0;i<cl;i++) { fileIO+="<td style='border-left:#000000 0.1pt solID; border-bottom:#000000 1.0pt solID; Font-size:15px;' align='center'><b>"+dt.Columns[i].Caption.ToString()+"</b></td>"; } fileIO=BeginTr.ToString()+fileIO.ToString()+EndTr.ToString(); //逐行处理数据 foreach(DaTarow row in myRow) { string OutIO=null; //当前数据写入 for(i=0;i<cl;i++) { OutIO+="<td style='border-left:#000000 0.1pt solID; border-bottom:#000000 1.0pt solID; Font-size:15px;' align='center'>"+row[i].ToString()+"</td>"; } MainIO+=BeginTr.ToString()+OutIO.ToString()+EndTr.ToString(); } fileIO="<center><table>"+TitleTab.ToString()+"<tr>"+BeginTab.ToString()+fileIO.ToString()+MainIO.ToString()+EndTab.ToString()+"</tr></table></center>"; resp.Write(fileIO.ToString()); resp.End(); } #endregion /// <summary> /// 导出Word文件类 /// </summary> /// <param name="ds"></param> /// <param name="filename"></param> /// #region //导出Word文件类 public voID DataSetToWord(DataSet ds,string filename) { try { //Web页面定义 //System.Web.UI.Page mypage=new System.Web.UI.Page(); httpResponse resp; resp=httpContext.Current.Response; resp.Clear(); resp.Buffer=true; resp.Charset="utf-8"; resp.ContentEnCoding=System.Text.EnCoding.GetEnCoding("utf-8"); resp.Appendheader("Content-disposition","attachment;filename="+filename+".doc"); resp.ContentType="application/ms-word"; //变量定义 string colheaders=null; string Is_item=null; //显示格式定义//////////////// //文件流 *** 作定义 // fileStream fs=new fileStream(filename,System.Text.EnCoding.GetEnCoding("GB2312")); StringWriter sfw=new StringWriter(); //定义表对象与行对象,同时用DataSet对其值进行初始化 System.Data.Datatable dt=ds.tables[0]; DaTarow[] myRow=dt.Select(); int i=0; int cl=dt.Columns.Count; //取得数据表各列标题,各标题之间以\t分割,最后一个列标题后加回车符 for(i=0;i<cl;i++) { //if(i==(cl-1)) //最后一列,加\n // colheaders+=dt.Columns[i].Caption.ToString(); //else colheaders+=dt.Columns[i].Caption.ToString()+"\t"; } sfw.Writeline(colheaders); //sw.Writeline(colheaders); //逐行处理数据 foreach(DaTarow row in myRow) { //当前数据写入 for(i=0;i<cl;i++) { //if(i==(cl-1)) // Is_item+=row[i].ToString()+"\n"; //else Is_item+=row[i].ToString()+"\t"; } sfw.Writeline(Is_item); //sw.Writeline(Is_item); Is_item=null; } resp.Write(sfw); //resp.Clear(); resp.End(); } catch(Exception e) { throw e; } } #endregion /// <summary> /// 数据集转换,即把DataSet转换为Word对象 /// </summary> /// <param name="ds"></param> /// <param name="Titlename"></param> /// #region // 运行HTML+CSS生成Word文件 public voID DataSetToWord(DataSet ds,string filename,string Titlename) { //调用Office //备注:速度太慢放弃应用此方法 //OWC.Word.Application oWord=new OWC.Word.ApplicationClass(); //OWC.Word._document odoc=new OWC.Word.documentClass(); string Exportfilename=null; if(filename==null || filename=="") Exportfilename="DFSOFT"; else Exportfilename=filename; if(Titlename=="" || Titlename==null) Titlename="添加标题处(高级报表)"; //定义表对象与行对象,同时用DataSet对其值进行初始化 System.Data.Datatable dt=ds.tables[0]; DaTarow[] myRow=dt.Select(); int i=0; int cl=dt.Columns.Count; #region// string filetitle="<center><table><tr><td><b>报表测试</b></td></tr></table>"+"\n";// string Endfile="</center>";// //Web页面定义 httpResponse resp; resp=httpContext.Current.Response; resp.Clear(); resp.ContentEnCoding=System.Text.EnCoding.GetEnCoding("utf-8"); resp.Appendheader("Content-disposition","attachment;filename="+Exportfilename+".doc"); resp.ContentType="application/vnd.ms-word";// System.IO.StringWriter oSW=new StringWriter();// System.Web.UI.HTMLTextWriter oHW=new System.Web.UI.HTMLTextWriter(oSW);// System.Web.UI.WebControls.DataGrID oDG=new System.Web.UI.WebControls.DataGrID();// oDG.DataSource=ds.tables[0];// oDG.DataBind();// oDG.RenderControl(oHW);// resp.Write(fileTitle.ToString()+oSW.ToString()+Endfile.ToString());// resp.End(); #endregion string BeginTab="<table border='0' cellpadding='0' cellspacing='0' style='border-right:#000000 0.1pt solID;border-top:#000000 0.1pt solID;'>"; string EndTab="</table>"; string fileIO=null; string MainIO=null; string TitleTab="<tr><td style='Font-size:13px;' align='center'><b>"+Titlename+"</b></td></tr><tr><td align='right' style='Font-size:15px;'>"+DateTime.Now.Year.ToString()+"年"+DateTime.Now.Month.ToString()+"月"+DateTime.Now.Day.ToString()+"日 </td></tr>"; string BeginTr="<tr>"; string EndTr="</tr>"; for(i=0;i<cl;i++) { fileIO+="<td style='border-left:#000000 0.1pt solID; border-bottom:#000000 1.0pt solID; Font-size:15px;' align='center'><b>"+dt.Columns[i].Caption.ToString()+"</b></td>"; } fileIO=BeginTr.ToString()+fileIO.ToString()+EndTr.ToString(); //逐行处理数据 foreach(DaTarow row in myRow) { string OutIO=null; //当前数据写入 for(i=0;i<cl;i++) { OutIO+="<td style='border-left:#000000 0.1pt solID; border-bottom:#000000 1.0pt solID; Font-size:15px;' align='center'>"+row[i].ToString()+"</td>"; } MainIO+=BeginTr.ToString()+OutIO.ToString()+EndTr.ToString(); } fileIO="<center><table>"+TitleTab.ToString()+"<tr>"+BeginTab.ToString()+fileIO.ToString()+MainIO.ToString()+EndTab.ToString()+"</tr></table></center>"; resp.Write(fileIO.ToString()); resp.End(); } #endregion }}更多关于C#相关内容感兴趣的读者可查看本站专题:《C# *** 作Excel技巧总结》、《C#中XML文件 *** 作技巧汇总》、《C#常见控件用法教程》、《WinForm控件用法总结》、《C#数据结构与算法教程》、《C#面向对象程序设计入门教程》及《C#程序设计之线程使用技巧总结》
希望本文所述对大家C#程序设计有所帮助。
总结以上是内存溢出为你收集整理的C#实现DataSet内数据转化为Excel和Word文件的通用类完整实例全部内容,希望文章能够帮你解决C#实现DataSet内数据转化为Excel和Word文件的通用类完整实例所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)