日期:2014-05-18 浏览次数:20475 次
public void CreateExcel2(DataTable dt, string fileName, Page page) { HttpResponse resp; resp = page.Response; //resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312"); //resp.AppendHeader("Content-Disposition", "attachment;filename=" + fileName); StringWriter sw = new StringWriter(); string colHeaders = "", ls_item = ""; ////定义表对象与行对象,同时用DataSet对其值进行初始化 //DataTable dt = ds.Tables[0]; DataRow[] myRow = dt.Select();//可以类似dt.Select("id>10")之形式达到数据筛选目的 int i = 0; int cl = dt.Columns.Count; colHeaders += "<table cellSpacing=\"0\" cellPadding=\"0\" width=\"100%\" >"; colHeaders += "<tr>"; //取得数据表各列标题,各标题之间以t分割,最后一个列标题后加回车符 for (i = 0; i < cl; i++) { if (i == (cl - 1))//最后一列,加n { colHeaders += "<td height=\"25\" width=\"30%\" align=\"center\" style=\"width: 10%\">" + dt.Columns[i].Caption.ToString() + "</td>"; } else { colHeaders += "<td height=\"25\" width=\"30%\" align=\"center\" style=\"width: 10%\">" + dt.Columns[i].Caption.ToString() + "</td>"; } } colHeaders += "</tr>"; //sw.Write(colHeaders); //resp.Write(colHeaders); //向HTTP输出流中写入取得的数据信息 //逐行处理数据 foreach (DataRow row in myRow) { //当前行数据写入HTTP输出流,并且置空ls_item以便下行数据 ls_item += "<tr>"; for (i = 0; i < cl; i++) { if (i == (cl - 1))//最后一列,加n { ls_item += "<td height=\"25\" width=\"30%\" align=\"center\" style=\"width: 10%\">" + row[i].ToString() + "</td>"; } else { ls_item += "<td height=\"25\" width=\"30%\" align=\"center\" style=\"width: 10%\">" + row[i].ToString() + "</td> "; } } //resp.Write(ls_item); ls_item += "</tr>"; } ls_item += "</table>"; sw.Write(colHeaders + ls_item); sw.Close(); resp.Clear(); resp.Buffer = false; resp.Charset = "UTF8"; resp.ContentEncoding = System.Text.Encoding.UTF8; resp.AppendHeader("Content-Disposition", "attachment;filename=" + fileName + ""); //Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312"); resp.ContentType = "application/ms-excel"; page.EnableViewState = false; resp.Write(sw.ToString()); resp.End(); }