在日常的項目中,Excel,Word,txt等格式的數據導入到數據庫中是很常見的,我在這裡做一下總結
這裡將分為Asp.net導入Sql Server,Oracle數據庫和WinForm導入Sql Server,Oracle數據庫
1,使用DataGird生成Excel
基本思想:
(1)將數據從數據庫中查詢出來,綁定到DataGrid控件中,這個DataGirdle控件知識作為數據的一個承載,不需要顯示在頁面中
(2)使用StringWriter將DataGrid讀出來,在使用Response的另存為功能,將html頁存為Xls格式的Excel文件。
代碼:
//導出按鈕
protected void ibtnExport_Click(object sender, ImageClickEventArgs e)
{
ExportDataGrid("application/ms-excel", "test.xls"); //導到Excel
}
具體實現
#region 使用DataGrid生成Excel
/// <summary>
/// 使用DataGrid生成Excel
/// </summary>
/// <param name="FileType">文件類型MIME類型</param>
/// <param name="FileName">文件名</param>
private void ExportDataGrid(string FileType, string FileName) //從DataGrid導出
{
System.Web.UI.WebControls.DataGrid dg = new System.Web.UI.WebControls.DataGrid();
//這裡使用的是IBatis與數據庫通信,大家可以使用ADO或者別的方式查詢數據
dg.DataSource = Helper.ContactExport().ExportDataIntoExcel();
dg.DataBind();
//定義文檔類型、字符編碼
Response.Clear();
Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, Encoding.UTF8).ToString());
Response.Charset = "UTF-8";
Response.ContentEncoding = Encoding.Default;
Response.ContentType = FileType;
dg.EnableViewState = false;
//定義一個輸入流
StringWriter tw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
//目標數據綁定到輸入流輸出
dg.RenderControl(hw);
//GvContract 綁定datagrid,或其他支持obj.RenderControl()屬性的控件
//ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "info", tw.ToString(), false);
Response.Write(tw.ToString());
Response.End();
}
#endregion
注意事項:
(1)由於我的頁面中有Ajax的UpdatePanel控件,所以在代碼中需要加入如下代碼:
public override void VerifyRenderingInServerForm(Control control)
{
//base.VerifyRenderingInServerForm(control);
}
(2)在UpdatePanel的Triggers節點下注冊按鈕
<Triggers>
<asp:PostBackTrigger ControlID="ibtnExport" />
</Triggers>
下面給出一個在網上下載的一個已經封裝好的類
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using System.Web.UI;
using System.Data;
using System.Text;
using System.Globalization;
using System.IO;
namespace VMS.Test.Classes
{
public class ExcelHelper {
#region Fields
string _fileName;
DataTable _dataSource;
string[] _titles = null;
string[] _fields = null;
int _maxRecords = 1000;
#endregion
#region Properties
/**//// <summary>
/// 限制輸出到Excel 的最大記錄數。超出則拋出異常
/// </summary>
public int MaxRecords {
set { _maxRecords = value; }
get { return _maxRecords; }
}
/**//// <summary>
/// 輸出到浏覽器的Excel 文件名
/// </summary>
public string FileName {
set { _fileName = value; }
get { return _fileName; }
}
#endregion
#region .ctor
/**//// <summary>
/// 構造函數
/// </summary>
/// <param name="titles">要輸出到Excel 的列標題的數組</param>
/// <param name="fields">要輸出到Excel 的字段名稱數組</param>
/// <param name="dataSource">數據源</param>
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;
}
/**//// <summary>
/// 構造函數
/// </summary>
/// <param name="titles">要輸出到Excel 的列標題的數組</param>
/// <param name="dataSource">數據源</param>
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;
}
/**//// <summary>
/// 構造函數
/// </summary>
/// <param name="dataSource">數據源</param>
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
/**//// <summary>
/// 導出到Excel 並提示下載
/// </summary>
/// <param name="dg">DataGrid</param>
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);
}
///**//// <summary>
///// 導出到Excel 並提示下載
///// </summary>
///// <param name="xgrid">ASPxGrid</param>
//public void Export(DataGrid 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);
//}
/**//// <summary>
/// 導出到Excel 並提示下載
/// </summary>
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("<meta http-equiv=\"Content-Type\" content=\"text/html;charset=GB2312\">");
DataGrid dg = c as DataGrid;
if (dg != null) {
dg.RenderControl(writer);
}
else {
DataGrid xgrid = c as DataGrid;
if (xgrid != null)
xgrid.RenderControl(writer);
else
throw new ArgumentException("only supports DataGrid or ASPxGrid.", "c");
}
c.Dispose();
response.Write(sw.ToString());
response.End();
}
/**//// <summary>
/// 得到一個隨意的文件名
/// </summary>
/// <returns></returns>
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");
}
} www.2cto.com
#endregion
}
}