日期:2014-05-18  浏览次数:20907 次

如何将文件输出流写进Excel模板呢?
我想把数据从sql中导出(asp.net)成excel文件,是以下面这种形式:
if (dt.Rows.Count > 0)
  {

  System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
  ///输出文件名
  System.Web.HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + strFileName.Trim() + ".xls");
  string colHeaders = "", ls_item = "";

  string n = "";
  string[] name = new string[dt.Columns.Count];
  //根据字段名录入标题
  for (int i = 0; i < dt.Columns.Count; i++)
  {
  n = dt.Columns[i].ColumnName.ToString();
  name[i] = n.Trim();
  if (i == dt.Columns.Count - 1)
  {
  colHeaders = n + "\n";
  }
  else
  { colHeaders = n + "\t"; }

  System.Web.HttpContext.Current.Response.Write(colHeaders);
  }

  ///循环输出该标题下的项目
  for (int j = 0; j < dt.Rows.Count; j++)
  {

  for (int k = 0; k < name.Length; k++)
  {
  if (k == name.Length - 1)
  {
  ls_item += "" + dt.Rows[j][name[k].Trim()].ToString() + "\t\n";
  }
  else
  {
  ls_item += "" + dt.Rows[j][name[k].Trim()].ToString() + "\t";
  }
  }
  System.Web.HttpContext.Current.Response.Write(ls_item);
  ls_item = "";
  }
  System.Web.HttpContext.Current.Response.ContentType = "application/octet-stream";
  System.Web.HttpContext.Current.Response.End();
  }
  dt.Clear();
  dt.Dispose();
  }
怎么才能吧他们写到一个制定格式的excel模板中去呢
急用!!!!!!!!

------解决方案--------------------
告诉你一个笨方法,先在后台按照格式生成表格,然后再导出到EXCEL;


Response.Clear();
Response.Write(str);//str是生成表格的字符串
Response.ContentType = "application/vnd.ms-Excel";
Response.AddHeader("Content-Disposition", "inline;filename=Plan.xls");
Response.End();