遇到了一个问题:需要从dataset中导出excel,要求如下: 1.不能使用excel对象,因为服务器在远端 2.生成的样式要和excel一样,不能出现白底等现象 过程:因为前期写了一个方法,实现了不使用excel对象导出,主要是用流方式,用html文件模拟的,但是问题是导出的excel显示的时候比较难看,有黑框和白底,视觉上不美观,想到过用css处理,但是由于不能控制一个sheet中的列的个数,最终放弃。 现在需要一个完美的解决方案。
protected void CreateExcel(DataSet ds,string fileName)
{
StringBuilder strb = new StringBuilder();
strb.Append("
strb.Append("xmlns:x=\"urn:schemas-microsoft-com:office:excel\"");
strb.Append("xmlns=\"http://www.w3.org/TR/REC-html40\"");
strb.Append("
");strb.Append("
strb.Append(".xl26");
strb.Append(" {mso-style-parent:style0;");
strb.Append(" font-family:\"Times New Roman\", serif;");
strb.Append(" mso-font-charset:0;");
strb.Append(" mso-number-format:\"@\";}");
strb.Append(" ");
strb.Append(" ");
strb.Append(" ");
strb.Append(" ");
strb.Append(" ");
strb.Append(" Sheet1 ");
strb.Append(" ");
strb.Append(" 285 ");
strb.Append(" ");
strb.Append(" ");
strb.Append(" ");
strb.Append(" 3 ");
strb.Append(" 1 ");
strb.Append(" ");
strb.Append(" ");
strb.Append(" False ");
strb.Append(" False ");
strb.Append(" False ");
strb.Append(" ");
strb.Append(" ");
strb.Append(" 6750 ");
strb.Append(" 10620 ");
strb.Append(" 480 ");
strb.Append(" 75 ");
strb.Append(" False ");
strb.Append(" False ");
strb.Append(" ");
strb.Append(" ");
strb.Append("");
strb.Append("
if (ds.Tables.Count > 0)
{
//写列标题
int columncount = ds.Tables[0].Columns.Count;
for (int columi = 0; columi < columncount; columi++)
{
strb.Append("
" + ds.Tables[0].Columns[columi] + " ");}
strb.Append("
");//写数据
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
strb.Append("
");for (int j = 0; j < ds.Tables[0].Columns.Count; j++)
{
strb.Append("
" + ds.Tables[0].Rows[i][j].ToString() + " ");}
strb.Append("
");}
}
strb.Append(" ");
Response.Clear();
Response.Buffer = true;
Response.Charset = "GB2312";
Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName);
Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");//设置输出流为简体中文
Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。
this.EnableViewState = false;
Response.Write(strb);
Response.End();
}