45fan.com - 路饭网

搜索: 您的位置主页 > 网络频道 > 阅读资讯:通过DataGrid输出Excel并进行格式化处理的方法

通过DataGrid输出Excel并进行格式化处理的方法

2016-09-02 06:55:26 来源:www.45fan.com 【

通过DataGrid输出Excel并进行格式化处理的方法

privatevoidPage_Load(objectsender,System.EventArgse)
{
DataGrid1.DataSource
=CreateDataSource();
DataGrid1.DataBind();
}

ICollectionCreateDataSource()
{
DataTabledt
=newDataTable();
DataRowdr;
dt.Columns.Add(
newDataColumn("身份证号码",typeof(string)));
dt.Columns.Add(
newDataColumn("图书单价",typeof(decimal)));
dt.Columns.Add(
newDataColumn("购买数量",typeof(Int32)));
dt.Columns.Add(
newDataColumn("总价格",typeof(decimal)));

for(inti=0;i<30;i++)
{
dr
=dt.NewRow();
dr[
0]="123456789123456789";
dr[
1]=100*i/3.0;
dr[
2]=i+5;
dr[
3]=(decimal)dr[1]*(int)dr[2];

dt.Rows.Add(dr);
}

DataViewdv
=newDataView(dt);

returndv;

}


privatevoidButton1_Click(objectsender,EventArgse)
{
Response.Clear();
Response.Buffer
=true;
Response.Charset
="GB2312";
Response.AppendHeader(
"Content-Disposition","attachment;filename=FileName.xls");
//设置输出流为简体中文
Response.ContentEncoding=System.Text.Encoding.GetEncoding("GB2312");
//设置输出文件类型为Excel文件
Response.ContentType="application/ms-excel";
EnableViewState
=true;
System.Globalization.CultureInfomyCItrad
=newSystem.Globalization.CultureInfo("ZH-CN",true);
System.IO.StringWriteroStringWriter
=newSystem.IO.StringWriter(myCItrad);
System.Web.UI.HtmlTextWriteroHtmlTextWriter
=newSystem.Web.UI.HtmlTextWriter(oStringWriter);
this.DataGrid1.RenderControl(oHtmlTextWriter);
Response.Write(oStringWriter.ToString());
Response.End();
}


privatevoidDataGrid1_ItemDataBound(objectsender,System.Web.UI.WebControls.DataGridItemEventArgse)
{

if(e.Item.ItemType==ListItemType.Item||e.Item.ItemType==ListItemType.AlternatingItem)
{
e.Item.Cells[
0].Attributes.Add("style","vnd.ms-excel.numberformat:@");
e.Item.Cells[
3].Attributes.Add("style","vnd.ms-excel.numberformat:¥#,###.00");
}
}
 

本文地址:http://www.45fan.com/a/question/71065.html
Tags: excel 输出 DataGrid
编辑:路饭网
关于我们 | 联系我们 | 友情链接 | 网站地图 | Sitemap | App | 返回顶部