除调用excel类,给每个单元格赋值外还可以使用另一种简单的方法
protected void EduceExcel(DataTable dt, string FileName) { HttpContext.Current.Response.Clear(); HttpContext.Current.Response.Buffer = true;//设置缓冲输出 HttpContext.Current.Response.Charset = "GB2312";//设置输出流的HTTP字符集
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=\"" + System.Web.HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8) + ".xls\""); HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312"); HttpContext.Current.Response.ContentType = "application/ms-"; //_page.EnableViewState = false;//是否保持视图状态 HttpContext.Current.Response.Write(HTML(dt)); HttpContext.Current.Response.End(); }
private string HTML(DataTable dt) {
StringBuilder strHtml = new StringBuilder(); int I = dt.Columns.Count; strHtml.Append("<table>"); strHtml.Append("<tr>"); for (int j = 0; j < I; j++) { strHtml.Append("<td>" + dt.Columns[j].ColumnName + "</td>"); } strHtml.Append("</tr>"); //int ii = 1; foreach (DataRow dr in dt.Rows) { strHtml.Append("<tr>"); //int I = dr.Table.Columns.Count; for (int i = 0; i < I; i++) { strHtml.Append(" <td>" + dr[i].ToString() + "</td>"); } strHtml.Append("</tr>"); } strHtml.Append("</table>");
return strHtml.ToString(); }