.net解决数据导出excel时的格式问题

在项目中一般都需要将报表数据导出到EXCEL中,但经常出现导出长串数据(如身份证)到EXCEL中后显示为科学计数法的格式,或者报表中显示为001的数据导出到Excel后成了1的格式。

下面简单介绍一下以上问题的解决方法:

1、首先,了解一下excel从web页面上导出的原理。当我们把这些数据发送到客户端时,我们想让客户端程序(浏览器)以excel的格式读
取它,所以把mime类型设为:application/vnd.ms-excel,当excel读取文件时会以每个cell的格式呈现数据,如果
cell没有规定的格式,则excel会以默认的格式去呈现该cell的数据。这样就给我们提供了自定义数据格式的空间,当然我们必须使用excel支持
的格式。下面就列出常用的一些格式:

1) 文本:vnd.ms-excel.numberformat:@

2) 日期:vnd.ms-excel.numberformat:yyyy/mm/dd

3) 数字:vnd.ms-excel.numberformat:#,##0.00

4) 货币:vnd.ms-excel.numberformat:¥#,##0.00

5) 百分比:vnd.ms-excel.numberformat: #0.00%

这些格式你也可以自定义,比如年月你可以定义为:yy-mm等等。那么知道了这些格式,怎么去把这些格式添加到cell中呢?下面以datagrid控件为例,介绍其格式化代码。

2、实例

 <html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>导出数据到Excel</title>
</head>
<body>
<form id="form1" runat="server">
<div> <asp:DataGrid ID="DataGrid1" runat="server"
onitemdatabound="DataGrid1_ItemDataBound" >
</asp:DataGrid>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="导出数据到Excel" /> </div>
</form>
</body>
</html>

前台

 using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts; namespace FLX.ComplexQuery
{
public partial class OutPutExcel : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DataGrid1.DataSource = CreateDataSource();
DataGrid1.DataBind();
} protected void Button1_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.Charset = "GB2312";
Response.AppendHeader("Content-Disposition", "attachment;filename=FileName.xls");
Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");//设置输出流为简体中文
Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。
this.EnableViewState = false;
System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo("ZH-CN", true);
System.IO.StringWriter oStringWriter = new System.IO.StringWriter(myCItrad);
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
this.DataGrid1.RenderControl(oHtmlTextWriter);
Response.Write(oStringWriter.ToString());
Response.End();
} ICollection CreateDataSource()
{ DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add(new DataColumn("身份证号码", typeof(string)));
dt.Columns.Add(new DataColumn("图书单价", typeof(decimal)));
dt.Columns.Add(new DataColumn("购买数量", typeof(Int32)));
dt.Columns.Add(new DataColumn("总价格", typeof(decimal)));
for (int i = ; i < ; i++)
{
dr = dt.NewRow(); dr[] = "";
dr[] = * i / 3.0;
dr[] = i + ;
dr[] = (decimal)dr[] * (Int32)dr[];
dt.Rows.Add(dr);
}
DataView dv = new DataView(dt);
return dv;
} protected void DataGrid1_ItemDataBound(object sender, DataGridItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
//将整个datagrid都格式化为文本格式
int datagridcolumns; //datagrid显示列的数量,
//获取显示列的数量可以从数据源那里进行获取
//比如绑定DataGrid的数据源是DataSet
//datagrid显示列的数量 = ds.tables[0].Columns.Count;
for (int i = ; i < datagridcolumns; i++)
{
e.Item.Cells[i].Attributes.Add("style", "vnd.ms-excel.numberformat:@");
} //对需要格式化的列进行格式化
//e.Item.Cells[0].Attributes.Add("style", "vnd.ms-excel.numberformat:@");
//e.Item.Cells[2].Attributes.Add("style", "vnd.ms-excel.numberformat::#,##0.00");
// e.Item.Cells[3].Attributes.Add("style", "vnd.ms-excel.numberformat:¥#,###.00");
}
}
}
}

后台

3、动态绑定数据源示例

 //导出
function GetExcel() {
var model = {};
model.CompanyName = mini.get("CompanyName").getValue();
model.DateFrom = mini.get("DateFrom").getValue();
model.DateTo = mini.get("DateTo").getValue();
var json = mini.encode(model);
window.open("EntReport/SoftwareRP/Export?model=" + json);
}

前台js方法

       /// <summary>
/// 导出Excel
/// </summary>
/// <param name="model"></param>
public void Export(string model)
{
DataTable table = new DataTable();
Dictionary<string, string> dic = new Dictionary<string, string>();
JavaScriptSerializer js = new JavaScriptSerializer();
dic = js.Deserialize<Dictionary<string, string>>(model);
System.Data.DataSet ds = new ZhishiPatent_BLL().QueryDataSet(dic);
table = ds.Tables[]; Response.Clear();
Response.Buffer = true;
Response.Charset = "GB2312";//UTF-8
Response.AppendHeader("Content-Disposition", "attachment;filename=" + "知识专利统计.xls");
Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
Response.ContentType = "application/ms-excel";
Response.Write(ImportToExcel(table));
Response.End();
}
/// <summary>
/// 设置样式
/// </summary>
/// <param name="table"></param>
/// <returns></returns>
private string ImportToExcel(DataTable table)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
DataGrid gv = new DataGrid();
gv.ItemDataBound += new DataGridItemEventHandler(gv_ItemDataBound);
gv.AlternatingItemStyle.BackColor = System.Drawing.Color.White;
gv.AlternatingItemStyle.ForeColor = System.Drawing.Color.FromArgb(, , );
gv.HeaderStyle.BackColor = System.Drawing.Color.FromArgb(, , );
gv.HeaderStyle.Font.Bold = true;
gv.HeaderStyle.ForeColor = System.Drawing.Color.White;
gv.HeaderStyle.VerticalAlign = VerticalAlign.Middle;
gv.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
gv.ItemStyle.BackColor = System.Drawing.Color.FromArgb(, , );
gv.ItemStyle.ForeColor = System.Drawing.Color.FromArgb(, , );
gv.DataSource = table;
gv.DataBind();
System.IO.StringWriter oStringWriter = new System.IO.StringWriter(new System.Globalization.CultureInfo("zh-CN"));
System.Web.UI.HtmlTextWriter ht = new System.Web.UI.HtmlTextWriter(oStringWriter);
gv.RenderControl(ht);
return oStringWriter.ToString();
} private void gv_ItemDataBound(object sender, DataGridItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
foreach (TableCell item in e.Item.Cells)
{
item.Attributes.Add("style", "vnd.ms-excel.numberformat: @"); }
e.Item.Cells[].HorizontalAlign = HorizontalAlign.Right;
} }

后台

上一篇:Python 生成随机验证码


下一篇:MySQL更新命令_UPDATE