C#導(dǎo)出Excel總結(jié)_第1頁
C#導(dǎo)出Excel總結(jié)_第2頁
C#導(dǎo)出Excel總結(jié)_第3頁
C#導(dǎo)出Excel總結(jié)_第4頁
C#導(dǎo)出Excel總結(jié)_第5頁
已閱讀5頁,還剩7頁未讀 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡(jiǎn)介

1、團(tuán)匣C#導(dǎo)岀Excel總結(jié)在中導(dǎo)岀Execl有兩種方法,一種是將導(dǎo)岀的文件存放在服務(wù)器某個(gè)文件夾下面,然后將文件地址輸出在瀏覽器上;一種是將文件直接將文件輸出流寫給瀏覽器。在Response輸岀時(shí),t分隔的數(shù)據(jù),導(dǎo)岀execl時(shí),等價(jià)于分列,n等價(jià)于換行。1、將整個(gè)html全部輸岀execl此法將html中所有的內(nèi)容,如按鈕,表格,圖片等全部輸岀到Execl中。Response.Clear();Response.Buffer=true;Response.AppendHeader("Content-Disposition","attachment;filename=

2、"+DateTime.Now.ToString("yyyyMMdd")+".xls");Response.ContentEncoding=System.Text.Encoding.UTF8;Response.ContentType="application/vnd.ms-excel"this.EnableViewState=false;這里我們利用了ContentType屬性,它默認(rèn)的屬性為text/html,這時(shí)將輸岀為超文本,即我們常見的網(wǎng)頁格式到客戶端,如果改為ms-excel將將輸岀excel格式,也就是說以電子表格

3、的格式輸岀到客戶端,這時(shí)瀏覽器將提示你下載保存。ContentType的屬性還包括:image/JPEG;text/HTML;image/GIF;vnd.ms-excel/msword。同理,我們也可以輸岀(導(dǎo)岀)圖片、word文檔等。下面的方法,也均用了這個(gè)屬性。2、將DataGrid控件中的數(shù)據(jù)導(dǎo)岀Execl上述方法雖然實(shí)現(xiàn)了導(dǎo)岀的功能,但同時(shí)把按鈕、分頁框等html中的所有輸岀信息導(dǎo)了進(jìn)去。而我們一般要導(dǎo)岀的是數(shù)據(jù),DataGrid控件上的數(shù)據(jù)。System.Web.UI.Controlctl=this.DataGrid1;/DataGrid1是你在窗體中拖放的控件HttpContext

4、.Current.Response.AppendHeader("Content-Disposition","attachment;filename=Excel.xls");HttpContext.Current.Response.Charset="UTF-8"HttpContext.Current.Response.ContentEncoding=System.Text.Encoding.Default;HttpContext.Current.Response.ContentType="application/ms-exce

5、l"ctl.Page.EnableViewState=false;System.IO.StringWritertw=newSystem.IO.StringWriter();System.Web.UI.HtmlTextWriterhw=newSystem.Web.UI.HtmlTextWriter(tw);ctl.RenderControl(hw);HttpContext.Current.Response.Write(tw.ToString();HttpContext.Current.Response.End();如果你的DataGrid用了分頁,它導(dǎo)岀的是當(dāng)前頁的信息,也就是它導(dǎo)岀的

6、是DataGrid中顯示的信息。而不是你select語句的全部信息。為方便使用,寫成方法如下:publicvoidDGToExcel(System.Web.UI.Controlctl)HttpContext.Current.Response.AppendHeader("Content-Disposition","attachment;filename=Excel.xls");HttpContext.Current.Response.Charset="UTF-8"HttpContext.Current.Response.ContentE

7、ncoding=System.Text.Encoding.Default;HttpContext.Current.Response.ContentType="application/ms-excel"ctl.Page.EnableViewState=false;System.IO.StringWritertw=newSystem.IO.StringWriter();System.Web.UI.HtmlTextWriterhw=newSystem.Web.UI.HtmlTextWriter(tw);ctl.RenderControl(hw);HttpContext.Curre

8、nt.Response.Write(tw.ToString();HttpContext.Current.Response.End();用法:DGToExcel(datagrid1);3、將DataSet中的數(shù)據(jù)導(dǎo)岀Execl有了上邊的思路,就是將在導(dǎo)岀的信息,輸岀(Response)客戶端,這樣就可以導(dǎo)岀了。那么把DataSet中的數(shù)據(jù)導(dǎo)岀,也就是把DataSet中的表中的各行信息,以ms-excel的格式Response到http流,這樣就OK了。說明:參數(shù)ds應(yīng)為填充有數(shù)據(jù)表的DataSet,文件名是全名,包括后綴名,如execl2006.xlspublicvoidCreateExcel(

9、DataSetds,stringFileName)HttpResponseresp;resp=Page.Response;resp.ContentEncoding=System.Text.Encoding.GetEncoding("GB2312");resp.AppendHeader("Content-Disposition","attachment;filename="+FileName);stringcolHeaders="",ls_item=""/定義表對(duì)象與行對(duì)象,同時(shí)用DataSet對(duì)

10、其值進(jìn)行初始化DataTabledt=ds.TablesO;DataRowmyRow=dt.Select();可以類似dt.Select("id>10")之形式達(dá)到數(shù)據(jù)篩選目的inti=0;intcl=dt.Columns.Count;/取得數(shù)據(jù)表各列標(biāo)題,各標(biāo)題之間以t分割,最后一個(gè)列標(biāo)題后加回車符for(i=0;i<cl;i+)if(i=(cl-1)最后一列,加ncolHeaders+=dt.Columnsi.Caption.ToString()+"n"elsecolHeaders+=dt.Columnsi.Caption.ToStrin

11、g()+"t"resp.Write(colHeaders);/向HTTP輸岀流中寫入取得的數(shù)據(jù)信息/逐行處理數(shù)據(jù)foreach(DataRowrowinmyRow)/當(dāng)前行數(shù)據(jù)寫入HTTP輸岀流,并且置空ls_item以便下行數(shù)據(jù)for(i=0;i<cl;i+)if(i=(cl-1)/最后一列,加nls_item+=rowi.ToString()+"n"elsels_item+=rowi.ToString()+"t"resp.Write(lstem);ls_item=""resp.End();4、將datav

12、iew導(dǎo)岀execl若想實(shí)現(xiàn)更加富于變化或者行列不規(guī)則的execl導(dǎo)岀時(shí),可用本法。publicvoidOutputExcel(DataViewdv,stringstr)/dv為要輸岀到Excel的數(shù)據(jù),str為標(biāo)題名稱GC.Collect();Applicationexcel;/=newApplication();introwlndex=4;intcolIndex=1;_WorkbookxBk;WorksheetxSt;excel=newApplicationClass();xBk=excel.Workbooks.Add(true);xSt=(_Worksheet)xBk.ActiveShe

13、et;/取得標(biāo)題/foreach(DataColumncolindv.Table.Columns)colIndex+;excel.Cells4,collndex=col.ColumnName;xSt.get_Range(excel.Cells4,collndex,excel.Cells4,collndex).HorizontalAlignment=XlVAlign.xlVAlignCenter;/設(shè)置標(biāo)題格式為居中對(duì)齊/取得表格中的數(shù)據(jù)/foreach(DataRowViewrowindv)rowIndex+;colIndex=1;foreach(DataColumncolindv.Table

14、.Columns)colIndex+;if(col.DataType=System.Type.GetType("System.DateTime")excel.CellsrowIndex,colIndex=(Convert.ToDateTime(rowcol.ColumnName.ToString().ToString("yyyy-MM-dd");xSt.get_Range(excel.CellsrowIndex,colIndex,excel.CellsrowIndex,colIndex).HorizontalAlignment=XlVAlign.xlVA

15、lignCenter;/設(shè)置日期型的字段格式為居中對(duì)齊elseif(col.DataType=System.Type.GetType("System.String")excel.CellsrowIndex,colIndex=+rowcol.ColumnName.ToString();xSt.get_Range(excel.CellsrowIndex,colIndex,excel.CellsrowIndex,colIndex).HorizontalAlignment=XIVAlign.xIVAlignCenter;/設(shè)置字符型的字段格式為居中對(duì)齊elseexcel.Cells

16、rowlndex,collndex=rowcol.ColumnName.ToString();/加載一個(gè)合計(jì)行/introwSum=rowIndex+1;intcolSum=2;excel.CellsrowSum,2="合計(jì)"xSt.get_Range(excel.CellsrowSum,2,excel.CellsrowSum,2).HorizontalAlignment=XlHAlign.xlHAlignCenter;/設(shè)置選中的部分的顏色/xSt.get_Range(excel.CellsrowSum,colSum,excel.CellsrowSum,collndex)

17、.Select();xSt.get_Range(excel.CellsrowSum,colSum,excel.CellsrowSum,collndex).Interior.Colorlndex=19;/設(shè)置為淺黃色,共計(jì)有56種/取得整個(gè)報(bào)表的標(biāo)題/excel.Cells2,2=str;/設(shè)置整個(gè)報(bào)表的標(biāo)題格式/xSt.get_Range(excel.Cells2,2,excel.Cells2,2).Font.Bold=true;xSt.get_Range(excel.Cells2,2,excel.Cells2,2).Font.Size=22;/設(shè)置報(bào)表表格為最適應(yīng)寬度/xSt.get_Ran

18、ge(excel.Cells4,2,excel.CellsrowSum,collndex).Select();xSt.get_Range(excel.Cells4,2,excel.CellsrowSum,collndex).Columns.AutoFit();/設(shè)置整個(gè)報(bào)表的標(biāo)題為跨列居中/xSt.get_Range(excel.Cells2,2,excel.Cells2,collndex).Select();xSt.get_Range(excel.Cells2,2,excel.Cells2,collndex).HorizontalAlignment=XlHAlign.xlHAlignCent

19、erAcrossSelection;/繪制邊框/xSt.get_Range(excel.Cells4,2,excel.CellsrowSum,collndex).Borders.LineStyle=1;xSt.get_Range(excel.Cells4,2,excel.CellsrowSum,2).BordersXlBorderslndex.xlEdgeLeft.Weight=XlBorderWeight.xlThick;/設(shè)置左邊線加粗xSt.get_Range(excel.Cells4,2,excel.Cells4,collndex).BordersXlBorderslndex.xlEd

20、geTop.Weight=XlBorderWeight.xlThick;/設(shè)置上邊線加粗xSt.get_Range(excel.Cells4,collndex,excel.CellsrowSum,collndex).BordersXlBordersIndex.xlEdgeRight.Weight=XlBorderWeight.xlThick;/設(shè)置右邊線加粗xSt.get_Range(excel.CellsrowSum,2,excel.CellsrowSum,collndex).BordersXlBordersIndex.xlEdgeBottom.Weight=XlBorderWeight.x

21、lThick;/設(shè)置下邊線加粗/顯示效果/excel.Visible=true;xSt.Export(Server.MapPath(".")+"W"+this.xlfile.Text+".xls",SheetExportActionEnum.ssExportActionNone,Microsoft.Office.Interop.OWC.SheetExportFormat.ssExportHTML);xBk.SaveCopyAs(Server.MapPath(".")+""+this.xlfile

22、.Text+".xls");ds=null;xBk.Close(false,null,null);excel.Quit();System.Runtime.lnteropServices.Marshal.ReleaseComObject(xBk);System.Runtime.lnteropServices.Marshal.ReleaseComObject(excel);System.Runtime.lnteropServices.Marshal.ReleaseComObject(xSt);xBk=null;excel=null;xSt=null;GC.Collect();s

23、tringpath=Server.MapPath(this.xlfile.Text+".xls");System.IO.Filelnfofile=newSystem.IO.Filelnfo(path);Response.Clear();Response.Charset="GB2312"Response.ContentEncoding=System.Text.Encoding.UTF8;/添加頭信息,為“文件下載/另存為“對(duì)話框指定默認(rèn)文件名Response.AddHeader("Content-Disposition","a

24、ttachment;filename="+Server.UrlEncode(file.Name);/添加頭信息,指定文件大小,讓瀏覽器能夠顯示下載進(jìn)度Response.AddHeader("Content-Length",file丄ength.ToString();/指定返回的是一個(gè)不能被客戶端讀取的流,必須被下載Response.ContentType="application/ms-excel"/把文件流發(fā)送到客戶端Response.WriteFile(file.FullName);/停止頁面的執(zhí)行Response.End();上面的方面,

25、均將要導(dǎo)岀的execl數(shù)據(jù),直接給瀏覽器輸岀文件流,下面的方法是首先將其存到服務(wù)器的某個(gè)文件夾中,然后把文件發(fā)送到客戶端。這樣可以持久的把導(dǎo)出的文件存起來,以便實(shí)現(xiàn)其它功能。5、將execl文件導(dǎo)岀到服務(wù)器上,再下載。二、winForm中導(dǎo)出Execl的方法:1、方法1:publicvoidOut2Excel(stringsTableName,stringurl)Excel.ApplicationoExcel=newExcel.Application();WorkbooksoBooks;WorkbookoBook;SheetsoSheets;WorksheetoSheet;RangeoCell

26、s;stringsFile="",sTemplate=""/System.Data.DataTabledt=TableOut(sTableName).Tables0;sFile=url+"myExcel.xls"sTemplate=url+"MyTemplate.xls"/oExcel.Visible=false;oExcel.DisplayAlerts=false;/定義一個(gè)新的工作簿oBooks=oExcel.Workbooks;oBooks.Open(sTemplate,Type.Missing,Type.M

27、issing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing);oBook=oBooks.get_Item(1);oSheets=oBook.Worksheets;oSheet=(Worksheet)oSheets.get_ltem;/命名該sheetoSheet.Name="Sheet1"oCells=oShee

28、t.Cells;/調(diào)用dumpdata過程,將數(shù)據(jù)導(dǎo)入到Excel中去DumpData(dt,oCells);/保存oSheet.SaveAs(sFile,Excel.XlFileFormat.xlTemplate,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Excel.XlSaveAsAccessMode.xlNoChange,Type.Missing,Type.Missing,Type.Missing);oBook.Close(false,Type.Missing,Type.Missing);/退岀Excel,并且釋放調(diào)用的COM

29、資源oExcel.Quit();GC.Collect();KillProcess("Excel");privatevoidKillProcess(stringprocessName)System.Diagnostics.Processmyproc=newSystem.Diagnostics.Process();/得到所有打開的進(jìn)程tryforeach(ProcessthisprocinProcess.GetProcessesByName(processName)if(!thisproc.CloseMainWindow()thisproc.Kill();catch(Excep

30、tionExc)thrownewException("",Exc);2、方法2:protectedvoidExportExcel()gridbind();if(ds1=null)return;stringsaveFileName=""/boolfileSaved=false;SaveFileDialogsaveDialog=newSaveFileDialog();saveDialog.DefaultExt="xls"saveDialog.Filter="Excel文件|*xls"saveDialog.FileNam

31、e="Sheet1"saveDialog.ShowDialog();saveFileName=saveDialog.FileName;if(saveFileName.IndexOf(":")<0)return;/被點(diǎn)了取消/excelapp.Workbooks.Open工程進(jìn)度表.xls)Excel.ApplicationxlApp=newExcel.Application();objectmissing=System.Reflection.Missing.Value;if(xlApp=null)MessageBox.Show("無法創(chuàng)建

32、Excel對(duì)象,可能您的機(jī)子未安裝Excel");return;Excel.Workbooksworkbooks=xlApp.Workbooks;Excel.Workbookworkbook=workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);取得Excel.Worksheetworksheet=(Excel.Worksheet)workbook.Worksheets1;sheet1Excel.Rangerange;stringoldCaption=Title_label.Text.Trim();longtotalCount=ds1.

33、Tables0.Rows.Count;longrowRead=0;floatpercent=O;worksheet.Cells1,1=Title_label.Text.Trim();/寫入字段for(inti=0;i<ds1.Tables0.Columns.Count;i+)0worksheet.Cells2,i+1=ds1.Tables0.Columns.ColumnName;range=(Excel.Range)worksheet.Cells2,i+1;range.lnterior.Colorlndex=15;range.Font.Bold=true;/寫入數(shù)值Caption.Vis

34、ible=true;for(intr=0;r<ds1.Tables0.Rows.Count;r+)for(inti=0;i<ds1.Tables0.Columns.Count;i+)worksheet.Cellsr+3,i+1=ds1.Tables0.Rowsr;rowRead+;+"%."percent=(float)(100*rowRead)/totalCount;this.Caption.Text="正在導(dǎo)岀數(shù)據(jù)"+percent.ToString("0.00")Application.DoEvents();work

35、sheet.SaveAs(saveFileName,missing,missing,missing,missing,missing,missing,missing,missing);this.Caption.Visible=false;this.Caption.Text=oldCaption;range=worksheet.get_Range(worksheet.Cells2,1,worksheet.Cellsds1.Tables0.Rows.Count+2,ds1.Tables0.Columns.Count);range.BorderAround(Excel.XlLineStyle.xlCo

36、ntinuous,Excel.XlBorderWeight.xlThin,Excel.XlColorlndex.xlColorlndexAutomatic,null);range.BordersExcel.XlBordersIndex.xllnsideHorizontal.ColorIndex=Excel.XlColorIndex.xlColorlndexAutomatic;range.BordersExcel.XlBordersIndex.xllnsideHorizontal.LineStyle=Excel.XlLineStyle.xlContinuous;range.BordersExce

37、l.XlBordersIndex.xllnsideHorizontal.Weight=Excel.XlBorderWeight.xlThin;if(ds1.Tables0.Columns.Count>1)range.BordersExcel.XIBordersIndex.xllnsideVertical.Colorlndex=Excel.XIColorIndex.xlColorlndexAutomatic;workbook.Close(missing,missing,missing);xlApp.Quit();三、附注:雖然都是實(shí)現(xiàn)導(dǎo)岀execl的功能,但在和winform的程序中,實(shí)現(xiàn)的代碼是各不相同的。在中,是在服務(wù)器端讀

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。

評(píng)論

0/150

提交評(píng)論