上篇博客,讲述初步导出Excel出现的问题。现在具体写一下导出Excel步骤。
对于大批量的数据,导出Excel的办法如下。
(1)使用DataTable导出Excel
其中使用StringWriter类:将信息写入字符串。其命名空间为:System.IO
具体的原理是:
首先读取DataTable中的列名,然后循环读取DataTable行值。
然后设置导出的编码,导出的类型。
最后输出StringWriter对象即可。
这种导出是将文件直接以文件流的形式输出到浏览器。
- private StringWriter GetStringWriter(DataTable dt)
- {
- StringWriter sw = new StringWriter();
- //读列名
- foreach (DataColumn dc in dt.Columns)
- sw.Write(dc.ColumnName + " ");
- //读列值
- //重新的一行
- sw.Write(sw.NewLine);
- if (dt != null)
- {
- foreach (DataRow dr in dt.Rows)
- {
- for (int i = 0; i < dt.Columns.Count; i++)
- {
- sw.Write(dr[i].ToString() + " ");
- }
- sw.Write(sw.NewLine);
- }
- }
- sw.Close();
- return sw;
- }
- protected void ExcelImport(DataTable dt, string ExportFileName)
- {
- StringWriter sw = GetStringWriter(dt);
- //当前编码
- HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
- //把输出的文件名进行编码
- string fileName = HttpUtility.UrlEncode (ExportFileName, System.Text.Encoding.UTF8);
- //文件名
- string str = "attachment;filename=" + fileName + ".xls";
- //把文件头输出,此文件头激活文件下载框
- HttpContext.Current.Response.AppendHeader("Content-Disposition", str);//http报头文件
- HttpContext.Current.Response.ContentType = "application/ms-excel";
- this.Page.EnableViewState = false;
- Response.Write(sw);
- Response.End();
- }
- protected void Button1_Click(object sender, EventArgs e)
- {
- DataTable dt = new SelectCourseManager().SelectByCollegeAndProperty(ddlCourseProperty.Text, ddlCollege.SelectedValue);
- if (dt.Rows.Count == 0)
- Page.ClientScript.RegisterStartupScript(Page.GetType(), "message", "<script language='javascriopt' defer>alert('没有数据,不需要导出哈');</script>");
- else
- {
- //导出Excel
- ExcelImport(dt, "课程");
- }
- }
在导出Excel的时候,最关键的是编码问题,不同的形式导出Excel编码形式不同,否则,导出的Excel文件中文显示乱码。在DataTable导出Excel的时候,当前输出的编码样式是简体中文GB2312
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
而其导出的文件名是:UTF8编码
string fileName = HttpUtility.UrlEncode (ExportFileName, System.Text.Encoding.UTF8);