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

下載本文檔

版權說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權,請進行舉報或認領

文檔簡介

1、  C#導出Excel總結(jié)       在中導出Execl有兩種方法,一種是將導出的文件存放在服務器某個文件夾下面,然后將文件地址輸出在瀏覽器上;一種是將文件直接將文件輸出流寫給瀏覽器。在Response輸出時,t分隔的數(shù)據(jù),導出execl時,等價于分列,n等價于換行。 1、將整個html全部輸出execl此法將html中所有的內(nèi)容,如按鈕,表格,圖片等全部輸出到Execl中。   Response.Clear();        Respons

2、e.Buffer=   true;        Response.AppendHeader("Content-Disposition","attachment;"+DateTime.Now.ToString("yyyyMMdd")+".xls");              Response.Co

3、ntentEncoding=System.Text.Encoding.UTF8;      Response.ContentType   =   "application/vnd.ms-excel"      this.EnableViewState   =   false;   這里我們利用了ContentType屬性,它默認的屬性為text/html,這時將輸出為超文本,即

4、我們常見的網(wǎng)頁格式到客戶端,如果改為ms-excel將將輸出excel格式,也就是說以電子表格的格式輸出到客戶端,這時瀏覽器將提示你下載保存。ContentType的屬性還包括:image/JPEG;text/HTML;image/GIF;vnd.ms-excel/msword 。同理,我們也可以輸出(導出)圖片、word文檔等。下面的方法,也均用了這個屬性。2、將DataGrid控件中的數(shù)據(jù)導出Execl上述方法雖然實現(xiàn)了導出的功能,但同時把按鈕、分頁框等html中的所有輸出信息導了進去。而我們一般要導出的是數(shù)據(jù),DataGrid控件上的數(shù)據(jù)。System.Web.UI.Control ct

5、l=this.DataGrid1;/DataGrid1是你在窗體中拖放的控件HttpContext.Current.Response.AppendHeader("Content-Disposition","attachment;"); HttpContext.Current.Response.Charset ="UTF-8"     HttpContext.Current.Response.ContentEncoding =System.Text.Encoding.Default; HttpCo

6、ntext.Current.Response.ContentType ="application/ms-excel"ctl.Page.EnableViewState =false;    System.IO.StringWriter  tw = new System.IO.StringWriter() ; System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter (tw); ctl.RenderControl(hw); HttpContext.Current.

7、Response.Write(tw.ToString(); HttpContext.Current.Response.End(); 如果你的DataGrid用了分頁,它導出的是當前頁的信息,也就是它導出的是DataGrid中顯示的信息。而不是你select語句的全部信息。為方便使用,寫成方法如下:public void DGToExcel(System.Web.UI.Control ctl)        HttpContext.Current.Response.AppendHeader("Content-Disposition&qu

8、ot;,"attachment;");    HttpContext.Current.Response.Charset ="UTF-8"        HttpContext.Current.Response.ContentEncoding =System.Text.Encoding.Default;    HttpContext.Current.Response.ContentType ="application/ms-excel"&

9、#160;  ctl.Page.EnableViewState =false;       System.IO.StringWriter  tw = new System.IO.StringWriter() ;    System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter (tw);    ctl.RenderControl(hw);    HttpContext.Current.Resp

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

11、括后綴名,如execl2006.xlspublic  void CreateExcel(DataSet ds,string )   HttpResponse resp;  resp = Page.Response;  resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");  resp.AppendHeader("Content-Disposition", "attachment;"+); 

12、    string colHeaders= "", ls_item=""     /定義表對象與行對象,同時用DataSet對其值進行初始化  DataTable dt=ds.Tables0;  DataRow myRow=dt.Select();/可以類似dt.Select("id>10")之形式達到數(shù)據(jù)篩選目的        int i=0;   

13、;      int cl=dt.Columns.Count;     /取得數(shù)據(jù)表各列標題,各標題之間以t分割,最后一個列標題后加回車符  for(i=0;i<cl;i+)  if(i=(cl-1)/最后一列,加n  colHeaders +=dt.Columnsi.Caption.ToString() +"n"   else  colHeaders+=dt.Columnsi.C

14、aption.ToString()+"t"           resp.Write(colHeaders);  /向HTTP輸出流中寫入取得的數(shù)據(jù)信息     /逐行處理數(shù)據(jù)    foreach(DataRow row in myRow)        /當前行數(shù)據(jù)寫入HTTP輸出流,并且置空ls_item以便下行數(shù)據(jù)  &

15、#160;   for(i=0;i<cl;i+)  if(i=(cl-1)/最后一列,加n  ls_item +=rowi.ToString()+"n"   else  ls_item+=rowi.ToString()+"t"      resp.Write(ls_item);  ls_item=""       

16、0;   resp.End();    4、將dataview導出execl若想實現(xiàn)更加富于變化或者行列不規(guī)則的execl導出時,可用本法。public void OutputExcel(DataView dv,string str)    /dv為要輸出到Excel的數(shù)據(jù),str為標題名稱    GC.Collect();    Application excel;/ = new Application();    int rowIndex=4;  &#

17、160; int colIndex=1;     _Workbook xBk;    _Worksheet xSt;     excel= new ApplicationClass();       xBk = excel.Workbooks.Add(true);        xSt = (_Worksheet)xBk.ActiveSheet;     /    /取得標題

18、   /    foreach(DataColumn col in dv.Table.Columns)        colIndex+;     excel.Cells4,colIndex = col.ColumnName;     xSt.get_Range(excel.Cells4,colIndex,excel.Cells4,colIndex).HorizontalAlignment = XlVAlign.xlVAlignCenter;/設

19、置標題格式為居中對齊        /    /取得表格中的數(shù)據(jù)    /    foreach(DataRowView row in dv)        rowIndex +;     colIndex = 1;     foreach(DataColumn col in dv.Table.Columns)       &#

20、160;  colIndex +;      if(col.DataType = System.Type.GetType("System.DateTime")            excel.CellsrowIndex,colIndex = (Convert.ToDateTime(rowcol.ColumnName.ToString().ToString("yyyy-MM-dd");   

21、60;   xSt.get_Range(excel.CellsrowIndex,colIndex,excel.CellsrowIndex,colIndex).HorizontalAlignment = XlVAlign.xlVAlignCenter;/設置日期型的字段格式為居中對齊           else       if(col.DataType = System.Type.GetType("System.String"

22、;)            excel.CellsrowIndex,colIndex = "'"+rowcol.ColumnName.ToString();       xSt.get_Range(excel.CellsrowIndex,colIndex,excel.CellsrowIndex,colIndex).HorizontalAlignment = XlVAlign.xlVAlignCenter;/設置字符型的字段格式為

23、居中對齊           else            excel.CellsrowIndex,colIndex = rowcol.ColumnName.ToString();                /    /加載一個合計行    /    i

24、nt rowSum = rowIndex + 1;    int colSum = 2;    excel.CellsrowSum,2 = "合計"    xSt.get_Range(excel.CellsrowSum,2,excel.CellsrowSum,2).HorizontalAlignment = XlHAlign.xlHAlignCenter;    /    /設置選中的部分的顏色    /    xSt.get_Rang

25、e(excel.CellsrowSum,colSum,excel.CellsrowSum,colIndex).Select();    xSt.get_Range(excel.CellsrowSum,colSum,excel.CellsrowSum,colIndex).Interior.ColorIndex = 19;/設置為淺黃色,共計有56種    /    /取得整個報表的標題    /    excel.Cells2,2 = str;    /   

26、; /設置整個報表的標題格式    /    xSt.get_Range(excel.Cells2,2,excel.Cells2,2).Font.Bold = true;    xSt.get_Range(excel.Cells2,2,excel.Cells2,2).Font.Size = 22;    /    /設置報表表格為最適應寬度    /    xSt.get_Range(excel.Cells4,2,excel.CellsrowSum,col

27、Index).Select();    xSt.get_Range(excel.Cells4,2,excel.CellsrowSum,colIndex).Columns.AutoFit();    /    /設置整個報表的標題為跨列居中    /    xSt.get_Range(excel.Cells2,2,excel.Cells2,colIndex).Select();    xSt.get_Range(excel.Cells2,2,excel.Cells2,colIn

28、dex).HorizontalAlignment = XlHAlign.xlHAlignCenterAcrossSelection;    /    /繪制邊框    /    xSt.get_Range(excel.Cells4,2,excel.CellsrowSum,colIndex).Borders.LineStyle = 1;    xSt.get_Range(excel.Cells4,2,excel.CellsrowSum,2).BordersXlBordersIndex.xlEdge

29、Left.Weight = XlBorderWeight.xlThick;/設置左邊線加粗    xSt.get_Range(excel.Cells4,2,excel.Cells4,colIndex).BordersXlBordersIndex.xlEdgeTop.Weight = XlBorderWeight.xlThick;/設置上邊線加粗    xSt.get_Range(excel.Cells4,colIndex,excel.CellsrowSum,colIndex).BordersXlBordersIndex.xlEdgeRight.Weigh

30、t = XlBorderWeight.xlThick;/設置右邊線加粗    xSt.get_Range(excel.CellsrowSum,2,excel.CellsrowSum,colIndex).BordersXlBordersIndex.xlEdgeBottom.Weight = XlBorderWeight.xlThick;/設置下邊線加粗    /    /顯示效果    /    excel.Visible=true;     /xSt.Export(

31、Server.MapPath(".")+""+this.xl".xls",SheetExportActionEnum.ssExportActionNone,Microsoft.Office.Interop.OWC.SheetExportFormat.ssExportHTML);    xBk.SaveCopyAs(Server.MapPath(".")+""+this.xl".xls");     ds = null; 

32、60;           xBk.Close(false, null,null);                 excel.Quit();             System.Runtime.InteropServices.Marshal.R

33、eleaseComObject(xBk);             System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);     System.Runtime.InteropServices.Marshal.ReleaseComObject(xSt);            

34、 xBk = null;             excel = null;    xSt = null;             GC.Collect();    string path = Server.MapPath(this.xl".xls");     System.IO. fi

35、le = new System.IO.(path);    Response.Clear();    Response.Charset="GB2312"    Response.ContentEncoding=System.Text.Encoding.UTF8;    / 添加頭信息,為"文件下載/另存為"對話框指定默認文件名    Response.AddHeader("Content-Disposition", "atta

36、chment; " + Server.UrlEncode();    / 添加頭信息,指定文件大小,讓瀏覽器能夠顯示下載進度    Response.AddHeader("Content-Length", ();        / 指定返回的是一個不能被客戶端讀取的流,必須被下載    Response.ContentType = "application/ms-excel"       

37、; / 把文件流發(fā)送到客戶端    Response.Write);    / 停止頁面的執(zhí)行       Response.End();       上面的方面,均將要導出的execl數(shù)據(jù),直接給瀏覽器輸出文件流,下面的方法是首先將其存到服務器的某個文件夾中,然后把文件發(fā)送到客戶端。這樣可以持久的把導出的文件存起來,以便實現(xiàn)其它功能。5、將execl文件導出到服務器上,再下載。二、winForm中導出Execl的方法:1、方法1:public void Out2Excel(

38、string sTableName,string url)Excel.Application oExcel=new Excel.Application();Workbooks oBooks;Workbook oBook;Sheets oSheets;Worksheet oSheet;Range oCells;string sFile="",sTemplate=""/System.Data.DataTable dt=TableOut(sTableName).Tables0;s"myExcel.xls"sTemplate=url+&quo

39、t;MyTemplate.xls"/oExcel.Visible=false;oExcel.DisplayAlerts=false;/定義一個新的工作簿oBooks=oExcel.Workbooks;oBooks.Open(sTemplate,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing, Type.Missing, Ty

40、pe.Missing);oBook=oBooks.get_Item(1);oSheets=oBook.Worksheets;oSheet=(Worksheet)oSheets.get_Item(1);/命名該sheetoSheet.Name="Sheet1"oCells=oSheet.Cells;/調(diào)用dumpdata過程,將數(shù)據(jù)導入到Excel中去DumpData(dt,oCells);/保存oSheet.SaveAs(s, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange, Type.Miss

41、ing, Type.Missing, Type.Missing);oBook.Close(false, Type.Missing,Type.Missing);/退出Excel,并且釋放調(diào)用的COM資源oExcel.Quit();GC.Collect();KillProcess("Excel");private void KillProcess(string processName)System.Diagnostics.Process myproc= new System.Diagnostics.Process();/得到所有打開的進程tryforeach (Process

42、thisproc in Process.GetProcessesByName(processName)if(!thisproc.CloseMainWindow()thisproc.Kill();catch(Exception Exc)throw new Exception("",Exc);2、方法2: protected void ExportExcel()     gridbind();   if(ds1=null) return;    st

43、ring save""/   bool ;   Save saveDialog=new Save();   saveDialog.DefaultExt ="xls"   saveDialog.Filter="Excel文件|*.xls"   saveDialog. ="Sheet1"   saveDialog.ShowDialog();&

44、#160;  save;   if(save(":")<0) return; /被點了取消/   excelapp.Workbooks.Open   (App.path & 工程進度表.xls)      Excel.Application xlApp=new Excel.Application();   object missing=System.Reflection.Missin

45、g.Value;    if(xlApp=null)       MessageBox.Show("無法創(chuàng)建Excel對象,可能您的機子未安裝Excel");    return;      Excel.Workbooks workbooks=xlApp.Workbooks;   Excel.Workbook workbook=workb

46、ooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);   Excel.Worksheet worksheet=(Excel.Worksheet)workbook.Worksheets1;/取得sheet1   Excel.Range range;       string oldCaption=Title_label .Text.Trim ();   long totalCount=ds1.Tab

47、les0.Rows.Count;   long rowRead=0;   float percent=0;    worksheet.Cells1,1=Title_label .Text.Trim ();   /寫入字段   for(int i=0;i<ds1.Tables0.Columns.Count;i+)       worksheet.Cells2,i+

48、1=ds1.Tables0.Columns.ColumnName;      range=(Excel.Range)worksheet.Cells2,i+1;    range.Interior.ColorIndex = 15;    range.Font.Bold = true;        /寫入數(shù)值   Caption .Visible = true;

49、0;  for(int r=0;r<ds1.Tables0.Rows.Count;r+)       for(int i=0;i<ds1.Tables0.Columns.Count;i+)         worksheet.Cellsr+3,i+1=ds1.Tables0.Rowsr;           

50、;  rowRead+;    percent=(float)(100*rowRead)/totalCount;        this.Caption.Text= "正在導出數(shù)據(jù)"+ percent.ToString("0.00")  +"%."    Application.DoEvents();     

51、; worksheet.SaveAs(save);      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);   rang

52、e.BorderAround(Excel.XlLineStyle.xlContinuous,Excel.XlBorderWeight.xlThin,Excel.XlColorIndex.xlColorIndexAutomatic,null);      range.BordersExcel.XlBordersIndex.xlInsideHorizontal.ColorIndex = Excel.XlColorIndex.xlColorIndexAutomatic;   range.BordersExcel.XlBo

53、rdersIndex.xlInsideHorizontal.LineStyle =Excel.XlLineStyle.xlContinuous;   range.BordersExcel.XlBordersIndex.xlInsideHorizontal.Weight =Excel.XlBorderWeight.xlThin;    if(ds1.Tables0.Columns.Count>1)       range.BordersExcel.XlBordersIndex.xlInsideVertical.ColorIndex=Excel.XlColorIndex.xlColorIndexAutomati

溫馨提示

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

評論

0/150

提交評論