公共类 ToExcel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Data;
/// <summary>
///ToExcel 导出excel
/// </summary>
public class ToExcel
{
public ToExcel()
{
}
public void ExcelExport(StringWriter sw, string exportFileName)
{
System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
//避免文件名称乱码
string fileName = HttpUtility.UrlEncode(exportFileName, System.Text.Encoding.UTF8);
string str = "attachment;filename=" + fileName + ".xls";
System.Web.HttpContext.Current.Response.AppendHeader("Content-Disposition", str);
System.Web.HttpContext.Current.Response.ContentType = "application/ms-excel";
System.Web.HttpContext.Current.Response.Write(sw);
System.Web.HttpContext.Current.Response.End();
}
public static StringWriter GetStringWriter(string[] sz, DataTable dt)
{
StringWriter sw = new StringWriter();
//先写列表头
for (int i = 0; i < sz.Length; i++)
{
sw.Write(sz[i] + "/t");
}
sw.Write(sw.NewLine);
//数据
if (dt != null)
{
//写数据
for (int i = 0; i < dt.Rows.Count; i++)
{
for (int j = 0; j < dt.Columns.Count ; j++)
{
sw.Write(dt.Rows[i][j].ToString() + "/t" );
}
sw.Write(sw.NewLine);
}
}
sw.Close();
return sw;
}
}
前台导出excel按钮 的事件
protected void btnExcel_Click(object sender, EventArgs e)
{
//excel表头数据
string[] strRange = new string[3];
strRange[0] = "客户编号";
strRange[1] = "物料号";
strRange[2] = "购买时间";
//excel表体数据
DataSet ds = DA_PromotionalOrder.GetSuccess(tj);
DataTable dt = ds.Tables[0];
ToExcel excel = new ToExcel();
StringWriter sw1 = ToExcel.GetStringWriter(strRange, dt);
excel.ExcelExport(sw1, "记录");
}
这种方式有个缺点,就是如果你往excel中插入的数据是以数字0开头,如:“0012121”,那么插入excel后是“12121”,当然我们也可以把StringWriter()方法与ExcelExport()方法添加到前台中,就不用写ToExcel.cs文件了