C#實(shí)現(xiàn)DataSet內(nèi)數(shù)據(jù)轉(zhuǎn)化為Excel和Word文件的通用類(lèi)完整實(shí)例
本文實(shí)例講述了C#實(shí)現(xiàn)DataSet內(nèi)數(shù)據(jù)轉(zhuǎn)化為Excel和Word文件的通用類(lèi)。分享給大家供大家參考,具體如下:
前不久因?yàn)轫?xiàng)目的需要寫(xiě)的一個(gè)C#把DataSet內(nèi)數(shù)據(jù)轉(zhuǎn)化為Excel和Word文件的通用類(lèi),這些關(guān)于Excel、Word的導(dǎo)出方法,基本可以實(shí)現(xiàn)日常須要,其中有些方法可以把數(shù)據(jù)導(dǎo)出后 生成Xml格式,再導(dǎo)入數(shù)據(jù)庫(kù)!有些屏蔽內(nèi)容沒(méi)有去掉,保留下來(lái)方便學(xué)習(xí)參考用之。 最后請(qǐng)引用Office相應(yīng)COM組件,導(dǎo)出Excel對(duì)象的一個(gè)方法要調(diào)用其中的一些方法和屬性。
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 的摘要說(shuō)明。 /// 作用:把DataSet數(shù)據(jù)集內(nèi)數(shù)據(jù)轉(zhuǎn)化為Excel、Word文件 /// 描述:這些關(guān)于Excel、Word的導(dǎo)出方法,基本可以實(shí)現(xiàn)日常須要,其中有些方法可以把數(shù)據(jù)導(dǎo)出后 /// 生成Xml格式,再導(dǎo)入數(shù)據(jù)庫(kù)!有些屏蔽內(nèi)容沒(méi)有去掉,保留下來(lái)方便學(xué)習(xí)參考用之。 /// 備注:請(qǐng)引用Office相應(yīng)COM組件,導(dǎo)出Excel對(duì)象的一個(gè)方法要調(diào)用其中的一些方法和屬性。 /// </summary> public class ExportFiles { /// <summary> /// /// </summary> /// #region //構(gòu)造函數(shù) public ExportFiles() { // // TODO: 在此處添加構(gòu)造函數(shù)邏輯 // } #endregion /// <summary> /// 調(diào)用Excel.dll導(dǎo)出Excel文件 /// </summary> /// <param name="ds"></param> /// #region // 調(diào)用Excel.dll導(dǎo)出Excel文件 /// <summary> /// /// </summary> /// <param name="ds">DataSet數(shù)據(jù)庥</param> /// <param name="Duser">登錄用戶(hù)(如session["username"].Tostring())可為null或空</param> /// <param name="titlename">添加一個(gè)報(bào)表標(biāo)題</param> /// <param name="filepath">指定文件在服務(wù)器上的存放地址(如:Server.MapPath("."))可為null或空</param> /// /// 為什么在這里設(shè)置個(gè)filepath? /// 原因如下:filepath接收的內(nèi)容是Server.MapPath(".")這個(gè)參數(shù)值,這個(gè)值在這本類(lèi)中對(duì) /// System.Web.HttpServerUtility HServer=new System.Web.HttpServerUtility()的引用出錯(cuò),因?yàn)闆](méi)有繼承Page類(lèi) /// 所以只能以傳值的形式調(diào)用了,你有好的辦法可以修改,那就再好不過(guò)了! 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 //屏蔽內(nèi)容 ///本來(lái)想用下面的這個(gè)辦法實(shí)現(xiàn)的,可在IIS中必須設(shè)置相關(guān)的權(quán)限 ///所以就放棄了,把代碼設(shè)置為屏蔽內(nèi)容,供學(xué)習(xí)參考! /// // Microsoft.Office.Interop.Excel.Application app=new Microsoft.Office.Interop.Excel.Application(); // // if(app==null) // { // throw new Exception("系統(tǒng)調(diào)用錯(cuò)誤(Excel.dll)"); // } // app.Application.Workbooks.Add(true); // WorkbookClass oBook=new WorkbookClass(); // WorksheetClass oSheet=new WorksheetClass(); // // //定義表對(duì)象與行對(duì)象,同時(shí)用DataSet對(duì)其值進(jìn)行初始化 // 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; // //取得數(shù)據(jù)表各列標(biāo)題 // 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 //定義表對(duì)象與行對(duì)象,同時(shí)用DataSet對(duì)其值進(jìn)行初始化 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); //添加標(biāo)題名稱(chēng) if(titlename=="" || titlename==null) xlsheet.ActiveSheet.Cells[col,col]="添加標(biāo)題處(高級(jí)報(bào)表)"; else xlsheet.ActiveSheet.Cells[col,col]=titlename.Trim(); //判斷傳值user是否為空 if(Duser=="" || Duser==null) userfile="DFSOFT"; else userfile=Duser; //設(shè)置標(biāo)題大小 xlsheet.get_Range(xlsheet.Cells[col,col],xlsheet.Cells[col,cl]).Font.set_Size(13); //加粗標(biāo)題 xlsheet.get_Range(xlsheet.Cells[col,col],xlsheet.Cells[col,cl]).Font.set_Bold(true); xlsheet.get_Range(xlsheet.Cells[colsecond,col],xlsheet.Cells[colsecond,cl]).Font.set_Bold(true); //設(shè)置標(biāo)題水平居中 xlsheet.get_Range(xlsheet.Cells,xlsheet.Cells).set_HorizontalAlignment(OWC.Owc11.XlHAlign.xlHAlignCenter); //設(shè)置單元格寬度 //xlsheet.get_Range(xlsheet.Cells,xlsheet.Cells).set_ColumnWidth(9); xlsheet.get_Range(xlsheet.Cells[colday,col],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,col],xlsheet.Cells[colday,cl]).set_HorizontalAlignment(OWC.Owc11.XlHAlign.xlHAlignRight); //取得數(shù)據(jù)表各列標(biāo)題,各標(biāo)題之間以\t分割,最后一個(gè)列標(biāo)題后加回車(chē)符 for(i=0;i<cl;i++) { xlsheet.ActiveSheet.Cells[colsecond,i+1]=dt.Columns[i].Caption.ToString(); } //逐行處理數(shù)據(jù) foreach(DataRow row in myRow) { //當(dāng)前數(shù)據(jù)寫(xiě)入 for(i=0;i<cl;i++) { xlsheet.ActiveSheet.Cells[colnumber,i+1]=row[i].ToString().Trim(); } colnumber++; } //設(shè)置邊框線(xiàn) xlsheet.get_Range(xlsheet.Cells[colsecond,col],xlsheet.Cells[colnumber-1,cl]).Borders.set_LineStyle(OWC.Owc11.XlLineStyle.xlContinuous); try { //xlsheet.get_Range(xlsheet.Cells[2,1],xlsheet.Cells[8,15]).set_NumberFormat("¥#,##0.00"); // System.Web.HttpServerUtility HServer=new System.Web.HttpServerUtility(); //HServer.MapPath(".")+"http://testowc.xls"; xlsheet.Export(filepath+"http://exportfiles//~$"+userfile+".xls",OWC.Owc11.SheetExportActionEnum.ssExportActionNone,OWC.Owc11.SheetExportFormat.ssExportXMLSpreadsheet); } catch(Exception e) { throw new Exception("系統(tǒng)調(diào)用錯(cuò)誤或有打開(kāi)的Excel文件!"+e); } //Web頁(yè)面定義 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+"http://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> /// 導(dǎo)出Excel文件類(lèi) /// </summary> /// <param name="ds"></param> /// <param name="FileName"></param> /// #region //導(dǎo)出Excel文件類(lèi) public void DataSetToExcel(DataSet ds,string FileName) { try { //Web頁(yè)面定義 //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(); //定義表對(duì)象與行對(duì)象,同時(shí)用DataSet對(duì)其值進(jìn)行初始化 System.Data.DataTable dt=ds.Tables[0]; DataRow[] myRow=dt.Select(); int i=0; int cl=dt.Columns.Count; //取得數(shù)據(jù)表各列標(biāo)題,各標(biāo)題之間以\t分割,最后一個(gè)列標(biāo)題后加回車(chē)符 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); //逐行處理數(shù)據(jù) foreach(DataRow row in myRow) { //當(dāng)前數(shù)據(jù)寫(xiě)入 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> /// 數(shù)據(jù)集轉(zhuǎn)換,即把DataSet轉(zhuǎn)換為Excel對(duì)象 /// </summary> /// <param name="ds"></param> /// <param name="FileName"></param> /// <param name="titlename"></param> /// #region //運(yùn)用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="添加標(biāo)題處(高級(jí)報(bào)表)"; //定義表對(duì)象與行對(duì)象,同時(shí)用DataSet對(duì)其值進(jìn)行初始化 System.Data.DataTable dt=ds.Tables[0]; DataRow[] myRow=dt.Select(); int i=0; int cl=dt.Columns.Count; //Web頁(yè)面定義 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(); //逐行處理數(shù)據(jù) foreach(DataRow row in myRow) { string OutIO=null; //當(dāng)前數(shù)據(jù)寫(xiě)入 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> /// 導(dǎo)出Word文件類(lèi) /// </summary> /// <param name="ds"></param> /// <param name="FileName"></param> /// #region //導(dǎo)出Word文件類(lèi) public void DataSetToWord(DataSet ds,string FileName) { try { //Web頁(yè)面定義 //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,FileMode.Create,FileAccess.Write); //StreamWriter sw=new StreamWriter(fs,System.Text.Encoding.GetEncoding("GB2312")); StringWriter sfw=new StringWriter(); //定義表對(duì)象與行對(duì)象,同時(shí)用DataSet對(duì)其值進(jìn)行初始化 System.Data.DataTable dt=ds.Tables[0]; DataRow[] myRow=dt.Select(); int i=0; int cl=dt.Columns.Count; //取得數(shù)據(jù)表各列標(biāo)題,各標(biāo)題之間以\t分割,最后一個(gè)列標(biāo)題后加回車(chē)符 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); //逐行處理數(shù)據(jù) foreach(DataRow row in myRow) { //當(dāng)前數(shù)據(jù)寫(xiě)入 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> /// 數(shù)據(jù)集轉(zhuǎn)換,即把DataSet轉(zhuǎn)換為Word對(duì)象 /// </summary> /// <param name="ds"></param> /// <param name="titlename"></param> /// #region // 運(yùn)行html+css生成Word文件 public void DataSetToWord(DataSet ds,string FileName,string titlename) { //調(diào)用Office //備注:速度太慢放棄應(yīng)用此方法 //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="添加標(biāo)題處(高級(jí)報(bào)表)"; //定義表對(duì)象與行對(duì)象,同時(shí)用DataSet對(duì)其值進(jìn)行初始化 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ào)表測(cè)試</b></td></tr></table>"+"\n"; // string EndFile="</center>"; // //Web頁(yè)面定義 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(); //逐行處理數(shù)據(jù) foreach(DataRow row in myRow) { string OutIO=null; //當(dāng)前數(shù)據(jù)寫(xiě)入 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 } }
更多關(guān)于C#相關(guān)內(nèi)容感興趣的讀者可查看本站專(zhuān)題:《C#操作Excel技巧總結(jié)》、《C#中XML文件操作技巧匯總》、《C#常見(jiàn)控件用法教程》、《WinForm控件用法總結(jié)》、《C#數(shù)據(jù)結(jié)構(gòu)與算法教程》、《C#面向?qū)ο蟪绦蛟O(shè)計(jì)入門(mén)教程》及《C#程序設(shè)計(jì)之線(xiàn)程使用技巧總結(jié)》
希望本文所述對(duì)大家C#程序設(shè)計(jì)有所幫助。
相關(guān)文章
ListView用法中與滾動(dòng)相關(guān)的需求實(shí)現(xiàn)
這篇文章主要介紹了ListView用法中與滾動(dòng)相關(guān)的需求實(shí)現(xiàn),獲取并設(shè)置ListView的滾動(dòng)位置,以及獲取滾動(dòng)位置處的項(xiàng)目,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-06-06C#實(shí)現(xiàn)DataTable轉(zhuǎn)TXT、CSV文件
這篇文章介紹了C#實(shí)現(xiàn)DataTable轉(zhuǎn)TXT、CSV文件的方法,文中通過(guò)示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-04-04C#使用Fleck實(shí)現(xiàn)創(chuàng)建WebSocket服務(wù)器
這篇文章主要為大家詳細(xì)介紹了C#如何使用Fleck實(shí)現(xiàn)創(chuàng)建WebSocket服務(wù)器,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-01-01基于Unity實(shí)現(xiàn)2D邊緣檢測(cè)
這篇文章主要介紹了如何利用Unity實(shí)現(xiàn)2D邊緣檢測(cè),從而達(dá)到人物描邊效果。文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解一下2022-04-04C#實(shí)現(xiàn)的二維數(shù)組排序算法示例
這篇文章主要介紹了C#實(shí)現(xiàn)的二維數(shù)組排序算法,涉及C#針對(duì)二維數(shù)組的遍歷、判斷、排序等相關(guān)操作技巧,需要的朋友可以參考下2017-12-12C#中LINQ to Objects查詢(xún)的實(shí)現(xiàn)
LINQ to Objects是LINQ技術(shù)在C#中的一種應(yīng)用,它專(zhuān)門(mén)用于對(duì)內(nèi)存中的對(duì)象集合進(jìn)行查詢(xún)和操作,本文就詳細(xì)的介紹C#中LINQ to Objects查詢(xún)的實(shí)現(xiàn),感興趣的可以了解一下2023-08-08