DataGrid 匯出到 Excel 的幫助類
//=============================================================================== // // 從 DataGrid 或資料來源中匯出資料到 Excel 並提示下載的幫助類。 // // Author: Roger Chen (木野狐) // Date: 2005-1-27 // Version: 1.22 // History: // v1.00 使用靜態方法的形式實現該類,提供多種過載方式。 // v1.01 新增了對 DevExpress.Web.ASPxGrid.ASPxGrid 的直接匯出支援。 // v1.20 改寫為實體類。 減少了重複程式碼。 // v1.21 2005-2-1 // 修改了一個建構函式的過載形式中異常檢測的程式碼。延遲到 Export() 方法。 // v1.22 2005-2-3 // 1. 修正了 Export() 方法中缺少 _titles != null 判斷的 bug. // 2. 修正了長的數字被 Excel 自動轉換為科學計數法的毛病。 // (修改的辦法來自 ) // //=============================================================================== namespace RChen.Demos {
using System;
using System.IO;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Globalization;
using System.Collections;
using DevExpress.Web.ASPxGrid;
public class ExcelHelper {
#region Fields
string _fileName;
DataTable _dataSource;
string[] _titles = null;
string[] _fields = null;
int _maxRecords = 1000;
#endregion
#region Properties
///
/// 限制輸出到 Excel 的最大記錄數。超出則丟擲異常
/// public int MaxRecords {
set { _maxRecords = value; }
get { return _maxRecords; }
}
///
/// 輸出到瀏覽器的 Excel 檔名
/// public string FileName {
set { _fileName = value; }
get { return _fileName; }
}
#endregion
#region .ctor
///
/// 建構函式
///
/// 要輸出到 Excel 的列標題的陣列
/// 要輸出到 Excel 的欄位名稱陣列
/// 資料來源 public ExcelHelper(string[] titles, string[] fields, DataTable dataSource): this(titles, dataSource) {
if (fields == null || fields.Length == 0)
throw new ArgumentNullException("fields");
if (titles.Length != fields.Length)
throw new ArgumentException("titles.Length != fields.Length", "fields");
_fields = fields;
}
///
/// 建構函式
///
/// 要輸出到 Excel 的列標題的陣列
/// 資料來源 public ExcelHelper(string[] titles, DataTable dataSource): this(dataSource) {
if (titles == null || titles.Length == 0)
throw new ArgumentNullException("titles");
//if (titles.Length != dataSource.Columns.Count)
// throw new ArgumentException("titles.Length != dataSource.Columns.Count", "dataSource");
_titles = titles;
}
///
/// 建構函式
///
/// 資料來源 public ExcelHelper(DataTable dataSource) {
if (dataSource == null)
throw new ArgumentNullException("dataSource");
// maybe more checks needed here (IEnumerable, IList, IListSource, ) ???
// 很難判斷,先簡單的使用 DataTable
_dataSource = dataSource;
}
public ExcelHelper() {}
#endregion
#region public Methods
///
/// 匯出到 Excel 並提示下載
///
/// DataGrid public void Export(DataGrid dg) {
if (dg == null)
throw new ArgumentNullException("dg");
if (dg.AllowPaging || dg.PageCount > 1)
throw new ArgumentException("paged DataGrid can't be exported.", "dg");
// 新增標題樣式 dg.HeaderStyle.Font.Bold = true;
dg.HeaderStyle.BackColor = System.Drawing.Color.LightGray;
RenderExcel(dg);
}
///
/// 匯出到 Excel 並提示下載
///
/// ASPxGrid public void Export(DevExpress.Web.ASPxGrid.ASPxGrid xgrid) {
if (xgrid == null)
throw new ArgumentNullException("xgrid");
if (xgrid.PageCount > 1)
throw new ArgumentException("paged xgird not can't be exported.", "xgrid");
// 新增標題樣式 xgrid.HeaderStyle.Font.Bold = true;
xgrid.HeaderStyle.BackColor = System.Drawing.Color.LightGray;
RenderExcel(xgrid);
}
///
/// 匯出到 Excel 並提示下載
/// public void Export() {
if (_dataSource == null)
throw new Exception("資料來源尚未初始化");
if (_fields == null && _titles != null && _titles.Length != _dataSource.Columns.Count)
throw new Exception("_titles.Length != _dataSource.Columns.Count");
if (_dataSource.Rows.Count > _maxRecords)
throw new Exception("匯出資料條數超過限制。請設定 MaxRecords 屬性以定義匯出的最多記錄數。");
DataGrid dg = new DataGrid();
dg.DataSource = _dataSource;
if (_titles == null) {
dg.AutoGenerateColumns = true;
}
else {
dg.AutoGenerateColumns = false;
int cnt = _titles.Length;
System.Web.UI.WebControls.BoundColumn col;
if (_fields == null) {
for (int i=0; i<cnt; i++) {
col = new System.Web.UI.WebControls.BoundColumn();
col.HeaderText = _titles[i];
col.DataField = _dataSource.Columns[i].ColumnName;
dg.Columns.Add(col);
}
}
else {
for (int i=0; i<cnt; i++) {
col = new System.Web.UI.WebControls.BoundColumn();
col.HeaderText = _titles[i];
col.DataField = _fields[i];
dg.Columns.Add(col);
}
}
}
// 新增標題樣式 dg.HeaderStyle.Font.Bold = true;
dg.HeaderStyle.BackColor = System.Drawing.Color.LightGray;
dg.ItemDataBound += new DataGridItemEventHandler(DataGridItemDataBound);
dg.DataBind();
RenderExcel(dg);
}
#endregion
#region private Methods
private void RenderExcel(Control c) {
// 確保有一個合法的輸出檔名 if (_fileName == null || _fileName == string.Empty || !(_fileName.ToLower().EndsWith(".xls")))
_fileName = GetRandomFileName();
HttpResponse response = HttpContext.Current.Response;
response.Charset = "GB2312";
response.ContentEncoding = Encoding.GetEncoding("GB2312");
response.ContentType = "application/ms-excel/msword";
response.AppendHeader("Content-Disposition", "attachment;filename=" +
HttpUtility.UrlEncode(_fileName));
CultureInfo cult = new CultureInfo("zh-CN", true);
StringWriter sw = new StringWriter(cult);
HtmlTextWriter writer = new HtmlTextWriter(sw);
writer.WriteLine(""Content-Type" content="text/html;charset=GB2312">");
DataGrid dg = c as DataGrid;
if (dg != null) {
dg.RenderControl(writer);
}
else {
ASPxGrid xgrid = c as ASPxGrid;
if (xgrid != null)
xgrid.RenderControl(writer);
else
throw new ArgumentException("only supports DataGrid or ASPxGrid.", "c");
}
c.Dispose();
response.Write(sw.ToString());
response.End();
}
///
/// 得到一個隨意的檔名
///
/// private string GetRandomFileName() {
Random rnd = new Random((int) (DateTime.Now.Ticks));
string s = rnd.Next(Int32.MaxValue).ToString();
return DateTime.Now.ToShortDateString() + "_" + s + ".xls";
}
private void DataGridItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e) {
if(e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) {
e.Item.Attributes.Add("style", "vnd.ms-excel.numberformat:@");
//e.Item.Cells[3].Attributes.Add("style", "vnd.ms-excel.numberformat:¥#,###.00"); }
}
#endregion
}
} [@more@]
using System;
using System.IO;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Globalization;
using System.Collections;
using DevExpress.Web.ASPxGrid;
public class ExcelHelper {
#region Fields
string _fileName;
DataTable _dataSource;
string[] _titles = null;
string[] _fields = null;
int _maxRecords = 1000;
#endregion
#region Properties
///
/// 限制輸出到 Excel 的最大記錄數。超出則丟擲異常
/// public int MaxRecords {
set { _maxRecords = value; }
get { return _maxRecords; }
}
///
/// 輸出到瀏覽器的 Excel 檔名
/// public string FileName {
set { _fileName = value; }
get { return _fileName; }
}
#endregion
#region .ctor
///
/// 建構函式
///
/// 要輸出到 Excel 的列標題的陣列
/// 要輸出到 Excel 的欄位名稱陣列
/// 資料來源 public ExcelHelper(string[] titles, string[] fields, DataTable dataSource): this(titles, dataSource) {
if (fields == null || fields.Length == 0)
throw new ArgumentNullException("fields");
if (titles.Length != fields.Length)
throw new ArgumentException("titles.Length != fields.Length", "fields");
_fields = fields;
}
///
/// 建構函式
///
/// 要輸出到 Excel 的列標題的陣列
/// 資料來源 public ExcelHelper(string[] titles, DataTable dataSource): this(dataSource) {
if (titles == null || titles.Length == 0)
throw new ArgumentNullException("titles");
//if (titles.Length != dataSource.Columns.Count)
// throw new ArgumentException("titles.Length != dataSource.Columns.Count", "dataSource");
_titles = titles;
}
///
/// 建構函式
///
/// 資料來源 public ExcelHelper(DataTable dataSource) {
if (dataSource == null)
throw new ArgumentNullException("dataSource");
// maybe more checks needed here (IEnumerable, IList, IListSource, ) ???
// 很難判斷,先簡單的使用 DataTable
_dataSource = dataSource;
}
public ExcelHelper() {}
#endregion
#region public Methods
///
/// 匯出到 Excel 並提示下載
///
/// DataGrid public void Export(DataGrid dg) {
if (dg == null)
throw new ArgumentNullException("dg");
if (dg.AllowPaging || dg.PageCount > 1)
throw new ArgumentException("paged DataGrid can't be exported.", "dg");
// 新增標題樣式 dg.HeaderStyle.Font.Bold = true;
dg.HeaderStyle.BackColor = System.Drawing.Color.LightGray;
RenderExcel(dg);
}
///
/// 匯出到 Excel 並提示下載
///
/// ASPxGrid public void Export(DevExpress.Web.ASPxGrid.ASPxGrid xgrid) {
if (xgrid == null)
throw new ArgumentNullException("xgrid");
if (xgrid.PageCount > 1)
throw new ArgumentException("paged xgird not can't be exported.", "xgrid");
// 新增標題樣式 xgrid.HeaderStyle.Font.Bold = true;
xgrid.HeaderStyle.BackColor = System.Drawing.Color.LightGray;
RenderExcel(xgrid);
}
///
/// 匯出到 Excel 並提示下載
/// public void Export() {
if (_dataSource == null)
throw new Exception("資料來源尚未初始化");
if (_fields == null && _titles != null && _titles.Length != _dataSource.Columns.Count)
throw new Exception("_titles.Length != _dataSource.Columns.Count");
if (_dataSource.Rows.Count > _maxRecords)
throw new Exception("匯出資料條數超過限制。請設定 MaxRecords 屬性以定義匯出的最多記錄數。");
DataGrid dg = new DataGrid();
dg.DataSource = _dataSource;
if (_titles == null) {
dg.AutoGenerateColumns = true;
}
else {
dg.AutoGenerateColumns = false;
int cnt = _titles.Length;
System.Web.UI.WebControls.BoundColumn col;
if (_fields == null) {
for (int i=0; i<cnt; i++) {
col = new System.Web.UI.WebControls.BoundColumn();
col.HeaderText = _titles[i];
col.DataField = _dataSource.Columns[i].ColumnName;
dg.Columns.Add(col);
}
}
else {
for (int i=0; i<cnt; i++) {
col = new System.Web.UI.WebControls.BoundColumn();
col.HeaderText = _titles[i];
col.DataField = _fields[i];
dg.Columns.Add(col);
}
}
}
// 新增標題樣式 dg.HeaderStyle.Font.Bold = true;
dg.HeaderStyle.BackColor = System.Drawing.Color.LightGray;
dg.ItemDataBound += new DataGridItemEventHandler(DataGridItemDataBound);
dg.DataBind();
RenderExcel(dg);
}
#endregion
#region private Methods
private void RenderExcel(Control c) {
// 確保有一個合法的輸出檔名 if (_fileName == null || _fileName == string.Empty || !(_fileName.ToLower().EndsWith(".xls")))
_fileName = GetRandomFileName();
HttpResponse response = HttpContext.Current.Response;
response.Charset = "GB2312";
response.ContentEncoding = Encoding.GetEncoding("GB2312");
response.ContentType = "application/ms-excel/msword";
response.AppendHeader("Content-Disposition", "attachment;filename=" +
HttpUtility.UrlEncode(_fileName));
CultureInfo cult = new CultureInfo("zh-CN", true);
StringWriter sw = new StringWriter(cult);
HtmlTextWriter writer = new HtmlTextWriter(sw);
writer.WriteLine(""Content-Type" content="text/html;charset=GB2312">");
DataGrid dg = c as DataGrid;
if (dg != null) {
dg.RenderControl(writer);
}
else {
ASPxGrid xgrid = c as ASPxGrid;
if (xgrid != null)
xgrid.RenderControl(writer);
else
throw new ArgumentException("only supports DataGrid or ASPxGrid.", "c");
}
c.Dispose();
response.Write(sw.ToString());
response.End();
}
///
/// 得到一個隨意的檔名
///
///
Random rnd = new Random((int) (DateTime.Now.Ticks));
string s = rnd.Next(Int32.MaxValue).ToString();
return DateTime.Now.ToShortDateString() + "_" + s + ".xls";
}
private void DataGridItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e) {
if(e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) {
e.Item.Attributes.Add("style", "vnd.ms-excel.numberformat:@");
//e.Item.Cells[3].Attributes.Add("style", "vnd.ms-excel.numberformat:¥#,###.00"); }
}
#endregion
}
} [@more@]
來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/631872/viewspace-905396/,如需轉載,請註明出處,否則將追究法律責任。
相關文章
- hive匯出到csv hive匯出到excelHiveExcel
- java 匯出到EXCELJavaExcel
- fastadmin的匯出到excel功能ASTExcel
- 將資料匯出到ExcelExcel
- C#中DataGrid匯出Excel檔案C#Excel
- Vue+element ui table 匯出到excelVueUIExcel
- 開源 - Ideal庫 - Excel幫助類,TableHelper實現(二)IdeaExcel
- 開源 - Ideal庫 - Excel幫助類,TableHelper實現(三)IdeaExcel
- 開源 - Ideal庫 - Excel幫助類,設計思路(一)IdeaExcel
- 開源 - Ideal庫 - Excel幫助類,ExcelHelper實現(四)IdeaExcel
- 開源 - Ideal庫 - Excel幫助類,ExcelHelper實現(五)IdeaExcel
- 將dataGridView內容匯出到Excel檔案ViewExcel
- NPOI幫助類
- Pgsql幫助類 netcoreSQLNetCore
- 使用 NPOI/DocX 二次封裝Office(Word、Excel)幫助類封裝Excel
- 多個報表匯出到一個 excel 的多 sheet 頁Excel
- 字元操作普通幫助類字元
- C# HTTP幫助類C#HTTP
- 第四節:海量資料匯出到Excel、百萬Excel匯入到DB、秒級/分鐘級排行版Excel
- Dynamics CRM 資料匯出到Excel時列標題不能重複Excel
- HExcel,一個簡單通用的匯入匯出Excel工具類Excel
- MSSQL資料匯出到MYSQLMySql
- 如何將simulink的影像匯出到VISIO中
- WPF WriteableBitmap透過GDI+繪製幫助類
- C#XmlHelper幫助類操作Xml文件的通用方法彙總C#XML
- 如何採集地圖上的店鋪把店鋪電話匯出到手機電腦excel地圖Excel
- 大文字資料,匯入匯出到資料庫資料庫
- poi的excel匯出Excel
- Vim官方的中文幫助!!
- 資料庫文件編寫,如何通過Navicat把表導成表格?資料庫快速匯出為excel表格資訊,excel匯出到word表格資料庫Excel
- java實現Excel定製匯出(基於POI的工具類)JavaExcel
- Linux幫助文件Linux
- jdk幫助文件JDK
- requests庫幫助
- 幫助文件(五)
- 匯出excelExcel
- EasyPoi, Excel資料的匯入匯出Excel
- vue excel匯入匯出VueExcel
- Unity匯出到Xcode沒有Run Destination的問題UnityXCode