.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;
} }
后台
.net解决数据导出excel时的格式问题的更多相关文章
- Gridview数据导出excel时身份证号码为科学计数法的解决方法
if (e.Row.RowType == DataControlRowType.DataRow) { string id = this.GridView1.DataKeys[e.Row.RowInde ...
- C#将网页数据导出Excel时编码设置
public void DGToExcel() { Response.ClearContent(); Response.Charset = "GB2312";//内容编码 Resp ...
- PHP导出excel时数字变为科学计数的解决方法
在数据导出到excel时数字格式不对,一般分为以下两种情况. 1.excel单元格设置长度不够 解决方法: //在excel.php文件中 $objActSheet = $objPHPExcel-&g ...
- 将页面中表格数据导出excel格式的文件(vue)
近期由于项目需要,需要将页面中的表格数据导出excel格式的文件,折腾了许久,在网上各种百度,虽然资料不少,但是大都不全,踩了许多坑,总算是皇天不负有心人,最后圆满解决了. 1.安装相关依赖(npm安 ...
- 用POI导出excel时,较长的数字不想被自动变为科学计数法的解决方式(转)
做过很多次导出excel了.都碰到一个问题,内容里如果包含一个比较长的数字,比如订单号“2546541656596”,excel会自动变成科学计数法... 弄过好几次都没有解决,最近又要导出excel ...
- Microsoft Dynamics CRM 解决数据大于5000时,页面上只能导出5000+数据。
页面显示: update [MSCRM_CONFIG].[dbo].[DeploymentProperties] set IntColumn=10000 --调整成10000+ 页面导出: 一.在 ...
- java解决poi导出excel文字水印,导出excel不可操作问题
首先需求是用户提出导出excel数据需使用水印备注其用途: 其实就是在导出excel的同时带有自定义文字水印的导出. 那么我们首先想到的肯定是以一个什么样的思路去解决该问题,首先查找poi导出exce ...
- Java使用POI实现数据导出excel报表
Java使用POI实现数据导出excel报表 在上篇文章中,我们简单介绍了java读取word,excel和pdf文档内容 ,但在实际开发中,我们用到最多的是把数据库中数据导出excel报表形式.不仅 ...
- 解决C#导出excel异常来自 HRESULT:0x800A03EC的方法 .
解决C#导出excel异常来自 HRESULT:0x800A03EC的方法 . xlBook.SaveAs(FilePath,Microsoft.Office.Interop.Excel.XlFi ...
随机推荐
- linux dynamic debug 官方教程
下载内核后,文档在:Documentation/dynamic-debug-howto.txt 中文版本:http://www.oschina.net/translate/dynamic-debug- ...
- file_get_contents微信头像等待时间过长的原因
UPDATE 2016/05/13 stackoverflow上的解决方法:http://stackoverflow.com/questions/3629504/php-file-get-conten ...
- Statement returned more than one row, where no more than one was expected
Statement returned more than one row, where no more than one was expected <resultMap id="Stu ...
- SQL&&LINQ:左(外)连接,右(外)连接,内连接,完全连接,交叉连接,多对多连接
SQL: 外连接和内连接: 左连接或左外连接:包含左边的表的所有行,如果右边表中的某行没有匹配,该行内容为空(NULL) --outer jion:left join or left outer jo ...
- Windows 域(domain)
http://baike.baidu.com/view/1512519.htm http://baike.baidu.com/view/1218493.htm http://www.jb51.net/ ...
- Filestream(读写)
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.I ...
- 用spring的InitializingBean作初始化
org.springframework.beans.factory包下有一个接口是InitializingBean 只有一个方法: /** * Invoked by a BeanFactory af ...
- Django1.9开发博客(13)- redis缓存
Redis 是一个高性能的key-value数据库.redis的出现, 很大程度补偿了memcached这类keyvalue存储的不足,在部分场合可以对关系数据库起到很好的补充作用. 它提供了Pyth ...
- Laravel Container分析
在分析Laravel流程具体细节之前我们先来了解一下它的Container容器,容器的作用简单的说就是用来存储对象(类名称或者实例),包括提供一些生成对象实例的方法. 我们查看Illuminate\C ...
- python窗体——pyqt初体验
连续两周留作业要写ftp的作业,从第一周就想实现一个窗体版本的,但是时间实在太短,qt零基础选手表示压力很大,幸好又延长了一周时间,所以也就有了今天这篇文章...只是为了介绍一些速成的方法,还有初学者 ...