.NET 导出Excel
生活随笔
收集整理的這篇文章主要介紹了
.NET 导出Excel
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
ExportData類:
View Code /// <summary>/// xxx/// 導出報表數據存入word或excel文件/// 2012-03-21/// </summary>public class ExportData{#region 構造函數public ExportData(){//// TODO: 在此處添加構造函數邏輯// }#endregion#region 導出頁面或web控件方法/// <summary>/// 將Web控件或頁面信息導出(不帶文件名參數)/// </summary>/// <param name="source">控件實例</param> /// <param name="DocumentType">導出類型:Excel或Word</param>public void ExportControl(System.Web.UI.Control source, string DocumentType){//設置Http的頭信息,編碼格式if (DocumentType == "Excel"){//Excel HttpContext.Current.Response.AppendHeader("Content-Disposition","attachment;filename="+ HttpUtility.UrlEncode("下載文件.xls",System.Text.Encoding.UTF8));HttpContext.Current.Response.ContentType = "application/ms-excel";}else if (DocumentType == "Word"){//WordHttpContext.Current.Response.AppendHeader("Content-Disposition","attachment;filename="+ HttpUtility.UrlEncode("下載文件.doc",System.Text.Encoding.UTF8));HttpContext.Current.Response.ContentType = "application/ms-word";}HttpContext.Current.Response.Charset = "UTF-8"; HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8; //關閉控件的視圖狀態source.Page.EnableViewState =false; //初始化HtmlWriterSystem.IO.StringWriter writer = new System.IO.StringWriter() ;System.Web.UI.HtmlTextWriter htmlWriter = new System.Web.UI.HtmlTextWriter(writer);source.RenderControl(htmlWriter); //輸出 HttpContext.Current.Response.Write(writer.ToString());HttpContext.Current.Response.End();}/// <summary>/// 將Web控件或頁面信息導出(帶文件名參數)/// </summary>/// <param name="source">控件實例</param> /// <param name="DocumentType">導出類型:Excel或Word</param>/// <param name="filename">保存文件名</param>public void ExportControl(System.Web.UI.Control source, string DocumentType, string filename){//設置Http的頭信息,編碼格式if (DocumentType == "Excel"){//Excel HttpContext.Current.Response.AppendHeader("Content-Disposition","attachment;filename="+ HttpUtility.UrlEncode(filename+".xls",System.Text.Encoding.UTF8));HttpContext.Current.Response.ContentType = "application/ms-excel"; }else if (DocumentType == "Word"){//WordHttpContext.Current.Response.AppendHeader("Content-Disposition","attachment;filename="+ HttpUtility.UrlEncode(filename+".doc",System.Text.Encoding.UTF8));HttpContext.Current.Response.ContentType = "application/ms-word";}HttpContext.Current.Response.Charset = "UTF-8"; HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8; //關閉控件的視圖狀態source.Page.EnableViewState =false; //初始化HtmlWriterSystem.IO.StringWriter writer = new System.IO.StringWriter() ;System.Web.UI.HtmlTextWriter htmlWriter = new System.Web.UI.HtmlTextWriter(writer);source.RenderControl(htmlWriter); //輸出 HttpContext.Current.Response.Write(writer.ToString());HttpContext.Current.Response.End();}#endregion#region 從DataSet到出到Excel/// <summary>/// 從DataSet到出到Excel方法一/// </summary>/// <param name="dtData">導出的數據</param>/// <param name="filename">導出的文件名</param>public void OutputExcel(System.Data.DataTable dtData, string filename) { System.Web.UI.WebControls.DataGrid dgExport = null; System.Web.HttpContext curContext = System.Web.HttpContext.Current; System.IO.StringWriter strWriter = null; System.Web.UI.HtmlTextWriter htmlWriter = null; if (dtData != null){curContext.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(filename + ".xls", System.Text.Encoding.UTF8));curContext.Response.ContentType = "application/vnd.ms-excel"; curContext.Response.ContentEncoding = System.Text.Encoding.UTF8; curContext.Response.Charset = ""; strWriter = new System.IO.StringWriter(); htmlWriter = new System.Web.UI.HtmlTextWriter(strWriter); dgExport = new System.Web.UI.WebControls.DataGrid(); dgExport.DataSource = dtData.DefaultView; dgExport.AllowPaging = false; dgExport.DataBind(); dgExport.RenderControl(htmlWriter); curContext.Response.Write(strWriter.ToString()); curContext.Response.End(); } }/// <summary>/// 導出Excel,需要導入com控件Microsoft Excel 12.0 Object Library/// </summary>/// <param name="dt">要導出的數據</param>/// <param name="isTitle">是否顯示表頭</param>public void OutputExcel(DataTable dt, bool isTitle){Excel.ApplicationClass MyExcel = new Excel.ApplicationClass();MyExcel.Application.Workbooks.Add(true);Excel._Worksheet sheet = (Excel._Worksheet)MyExcel.Workbooks[1].Worksheets[1];sheet.Name = "sheet1";try{if (isTitle){for (int i = 0; i < dt.Columns.Count; i++){MyExcel.Cells[1, i + 1] = dt.Columns[i].ColumnName;//生成表頭 }MyExcel.get_Range(MyExcel.Cells[1, 1], MyExcel.Cells[1, dt.Columns.Count]).Font.Bold = true;MyExcel.get_Range(MyExcel.Cells[1, 1], MyExcel.Cells[1, dt.Columns.Count]).Font.Size = 12;MyExcel.get_Range(MyExcel.Cells[1, 1], MyExcel.Cells[1, dt.Columns.Count]).HorizontalAlignment = Excel.XlVAlign.xlVAlignCenter; //設置對齊方式MyExcel.get_Range(MyExcel.Cells[1, 1], MyExcel.Cells[1, dt.Columns.Count]).Borders.LineStyle = "1";}int Rows = 1;for (int i = 0; i < dt.Rows.Count; i++){Rows += 1;for (int j = 0; j < dt.Columns.Count; j++){MyExcel.Cells[Rows, j + 1] = "" + dt.Rows[i][j].ToString();//導入數據 }MyExcel.get_Range(MyExcel.Cells[Rows, 1], MyExcel.Cells[Rows, dt.Columns.Count]).Borders.LineStyle = "1";}sheet.Columns.AutoFit();//自動適應寬度MyExcel.Visible = true;}catch (Exception) { }finally { }}/// <summary>/// 導出一定格式的Excle,需要導入com控件Microsoft Excel 12.0 Object Library/// </summary>/// <param name="strTitle">標題</param>/// <param name="dt">數據源</param>/// <param name="isTitle">是否顯示列名</param>public void OutputExcel(string strTitle, DataTable dt, bool isTitle){Excel.ApplicationClass MyExcel = new Excel.ApplicationClass();MyExcel.Application.Workbooks.Add(true);Excel._Worksheet sheet = (Excel._Worksheet)MyExcel.Workbooks[1].Worksheets[1];//System.Web.HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(strTitle + ".xls", System.Text.Encoding.UTF8));sheet.Name = "sheet1";try{MyExcel.get_Range(MyExcel.Cells[1, 1], MyExcel.Cells[1, dt.Columns.Count]).MergeCells = true;//合并Excle單元格 MyExcel.get_Range(MyExcel.Cells[1, 1], MyExcel.Cells[1, dt.Columns.Count]).Font.Bold = true; //設置字體MyExcel.get_Range(MyExcel.Cells[1, 1], MyExcel.Cells[1, dt.Columns.Count]).Font.Size = 20;MyExcel.get_Range(MyExcel.Cells[1, 1], MyExcel.Cells[1, dt.Columns.Count]).HorizontalAlignment = Excel.XlVAlign.xlVAlignCenter; //設置對齊方式 MyExcel.Cells[1, 1] = strTitle;if (isTitle){for (int i = 0; i < dt.Columns.Count; i++){MyExcel.Cells[2, i + 1] = dt.Columns[i].ColumnName;//生成表頭 }MyExcel.get_Range(MyExcel.Cells[2, 1], MyExcel.Cells[2, dt.Columns.Count]).Font.Bold = true;MyExcel.get_Range(MyExcel.Cells[2, 1], MyExcel.Cells[2, dt.Columns.Count]).Font.Size = 12;MyExcel.get_Range(MyExcel.Cells[2, 1], MyExcel.Cells[2, dt.Columns.Count]).HorizontalAlignment = Excel.XlVAlign.xlVAlignCenter; //設置對齊方式MyExcel.get_Range(MyExcel.Cells[2, 1], MyExcel.Cells[2, dt.Columns.Count]).Borders.LineStyle = "1";}int Rows = 2;for (int i = 0; i < dt.Rows.Count; i++){Rows += 1;for (int j = 0; j < dt.Columns.Count; j++){MyExcel.Cells[Rows, j + 1] = "" + dt.Rows[i][j].ToString();//導入數據 }MyExcel.get_Range(MyExcel.Cells[Rows, 1], MyExcel.Cells[Rows, dt.Columns.Count]).Borders.LineStyle = "1";}sheet.Columns.AutoFit();//自動適應寬度MyExcel.Visible = true;}catch (Exception) { }finally { }}#endregion #region 調用說明//方法ExportControl(System.Web.UI.Control source, string DocumentType,string filename)中//第一個參數source表示導出的頁面或控件名,當為datagrid或dataList控件時,在導出Excel/word文件時,必須把控件的分頁、排序等屬性去除并重新綁定,//第二個參數DocumentType表示導出的文件類型word或excel//第三個參數filename表示需要導出的文件所取的文件名//調用方法://ExportData export=new ExportData(); //export.ExportControl(this, "Word","testfilename");//當為this時表示當前頁面//這是將整個頁面導出為Word,并命名為testfilename#endregion?注:選用ExportControl()方法時
MSDN對該方法的解釋如下:
必須位于 <form runat=server> 標記中的控件可以在呈現之前調用此方法,以便在控件被置于標記外時顯示錯誤信息。發送回或依賴于注冊的腳本塊的控件應該在?Control.Render?方法的重寫中調用此方法。呈現服務器窗體元素的方式不同的頁可以重寫此方法以在不同的條件下引發異常。
如果回發或使用客戶端腳本的服務器控件沒有包含在 HtmlForm 服務器控件 (<form runat="server">) 標記中,它們將無法正常工作。這些控件可以在呈現時調用該方法,以在它們沒有包含在 HtmlForm 控件中時提供明確的錯誤信息。
開發自定義服務器控件時,通常在為任何類型的輸入標記重寫 Render 方法時調用該方法。這在輸入控件調用?GetPostBackEventReference?或發出客戶端腳本時尤其重要。復合服務器控件不需要作出此調用。
? ? ? 2.提示:******,則需在前臺頁面添加“EnableEventValidation="false"”,如:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="****.aspx.cs" EnableEventValidation="false" Inherits="**.***.****" %>?
?
轉載于:https://www.cnblogs.com/captainR/archive/2012/07/26/ExportData.html
總結
以上是生活随笔為你收集整理的.NET 导出Excel的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 常用的 Web Service 服务汇总
- 下一篇: [转载] 坚强的心