DataTable导出Excel
public
static
void
DataTable1Excel(System.Data.DataTable dtData)
{
System.Web.UI.WebControls.GridView gvExport =
null
;
// 当前对话
System.Web.HttpContext curContext = System.Web.HttpContext.Current;
// IO用于导出并返回excel文件
System.IO.StringWriter strWriter =
null
;
System.Web.UI.HtmlTextWriter htmlWriter =
null
;
if
(dtData !=
null
)
{
// 设置编码和附件格式
curContext.Response.ContentType =
"application/vnd.ms-excel"
;
curContext.Response.ContentEncoding = System.Text.Encoding.GetEncoding(
"gb2312"
);
curContext.Response.Charset =
"utf-8"
;
// 导出excel文件
strWriter =
new
System.IO.StringWriter();
htmlWriter =
new
System.Web.UI.HtmlTextWriter(strWriter);
// 为了解决gvData中可能进行了分页的情况,需要重新定义一个无分页的GridView
gvExport =
new
System.Web.UI.WebControls.GridView();
dtData.Columns[
"id"
].ColumnName =
"编号"
;
dtData.Columns[
"deptName"
].ColumnName =
"部门名称"
;
dtData.Columns[
"trueName"
].ColumnName =
"员工姓名"
;
dtData.Columns[
"sname"
].ColumnName =
"工作量名称"
;
dtData.Columns[
"writeDate"
].ColumnName =
"录入日期"
;
dtData.Columns[
"selectDate"
].ColumnName =
"业务时间"
;
dtData.Columns[
"workloadYear"
].ColumnName =
"年份"
;
dtData.Columns[
"workloadMonth"
].ColumnName =
"期数"
;
dtData.Columns[
"pc"
].ColumnName =
"批次"
;
dtData.Columns[
"trueValue"
].ColumnName =
"工作量(单位次)"
;
//dtData.Columns["endScores"].ColumnName = "分值";
//dtData.Columns["totalScores"].ColumnName = "总分值";
//dtData.Columns["gwName"].ColumnName = "岗位名称";
gvExport.DataSource = dtData.DefaultView;
gvExport.AllowPaging =
false
;
gvExport.DataBind();
// 返回客户端
gvExport.RenderControl(htmlWriter);
curContext.Response.Write(
"<meta http-equiv=\"Content-Type\" content=\"text/html; charset=gb2312\" />"
+ strWriter.ToString());
curContext.Response.End();
}
}
You Must Try !