日期:2014-05-17 浏览次数:20531 次
datetable doclist=。。。。。。。。。。。
调用ExportToExcel.ExportExcel(Page, doclist, "规范文件", "规范文件");
/// <summary>
/// 构建TABLE加上头
/// </summary>
/// <param name="page"></param>
/// <param name="dtExcel"></param>
/// <param name="strFileName"></param>
public static void ExportExcel(System.Web.UI.Page page, System.Data.DataTable dtExcel, string head, string strFileName)
{
string strExtFile = strFileName.Trim();
if (strExtFile.Substring(strExtFile.Length - 4, 4).ToUpper() != ".xls")
{
strExtFile += ".xls";
}
page.Response.Clear();
page.Response.Buffer = true;
page.Response.Charset = "utf-8";
page.Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
page.Response.AppendHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(strExtFile, System.Text.Encoding.UTF8));
page.Response.ContentType = "application/vnd.ms-excel";
page.Response.Charset = "";
page.EnableViewState = false;
StringWriter stringWrite = new StringWriter();
HtmlTextWriter htmlTxtWrite = new HtmlTextWriter(stringWrite);
htmlTxtWrite.Write("<html>\r\n<meta content=\"text/html;charset=utf-8\"></meta>\r\n<body>\r\n");
htmlTxtWrite.Write("<table cellspacing=\"0\" border=\"1\">\r\n");
htmlTxtWrite.Write(head);
htmlTxtWrite.Write("<tr>\r\n");
for (int i = 0; i < dtExcel.Columns.Count; i++)
{
string strTitle = ConvertToHtmlCode(dtExcel.Columns[i].Caption.Trim());
htmlTxtWrite.Write("\t<td bgcolor=\"lightblue\">" + strTitle + "</td>\r\n");
}
htmlTxtWrite.Write("</tr>\r\n");
foreach (DataRow dr in dtExcel.Rows)
{
htmlTxtWrite.Write("<tr>\r\n");
for (int i = 0; i < dtExcel.Columns.Count; i++)
{
string strValue = "";
if (dtExcel.Columns[i].DataType == typeof(System.DateTime))
{
strValue = DateTimeConvertToString(dr[i]);
}
else
{
strValue = ConvertToHtmlCode(dr[i].ToString().Trim());
}
htmlTxtWrite.Write("\t<td>" + strValue + "</td>\r\n");
}
htmlTxtWrite.Write("</tr>\r\n");
}
htmlTxtWrite.Write("\r\n</table>\r\n</body>\r\n</html>");
page.Response.Write(stringWrite.ToString());
page.Response.End();
}