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

如何将数据导成ANSI编码格式的文本文件
系统:win2000server
环境:VS2005 C#.net
 //将dt导出到文本中.-- DataTable To/2 Text 用','隔开
  protected void ExportToText(System.Data.DataTable dtData)
  {
  // 当前对话 
  System.Web.HttpContext curContext = System.Web.HttpContext.Current;
  // IO用于导出并返回Text文件 
  System.IO.StringWriter strWriter = null;

  if (dtData != null)
  {
  // 设置编码和附件格式 
  curContext.Response.ContentType = "text/plain";
  curContext.Response.ContentEncoding = System.Text.Encoding.UTF8;

  //curContext.Response.Charset = "UTF-8";
  //curContext.Response.Charset = "us-ascii"; 
  curContext.Response.Charset = "Auto";
  curContext.Response.AppendHeader("Content-Disposition", "attachment;filename=" + DateTime.Now.ToString("yyyyMMdd") + "FreePolicy.txt");
  // 导出文本文件 
  strWriter = new System.IO.StringWriter();

  StringBuilder colSb = new StringBuilder();
  for (int k = 0; k < dtData.Columns.Count; k++)
  {
  //colSb.AppendFormat("{0},", dtData.Columns[k].ToString());//表的列名(字段名)
  colSb.AppendFormat("{0}\t", dtData.Columns[k].ToString());//表的列名(字段名)
  }
  colSb.AppendFormat("{0}\t", "");//增加一个tab
  string col = colSb.ToString();
  strWriter.WriteLine(col.ToString());

  StringBuilder rowInfoSb = new StringBuilder();
  string rowInfo = null;
  for (int i = 0; i < dtData.Rows.Count; i++)
  {
  for (int k = 0; k < dtData.Columns.Count; k++)
  {
  //rowInfoSb.AppendFormat("'{0}',", dtData.Rows[i][k].ToString());
  rowInfoSb.AppendFormat("{0}\t", dtData.Rows[i][k].ToString());
  }
  rowInfoSb.AppendFormat("{0}\t", "");//增加一个tab
  rowInfo = rowInfoSb.ToString() ;
  strWriter.WriteLine(rowInfo.ToString());
  rowInfoSb.Remove(0, rowInfoSb.Length);
  }

  strWriter.Close();
  curContext.Response.Write(strWriter.ToString());
  curContext.Response.End();
  }
  }

这样导出的为UTF-8 的格式,如何导成ANSI的格式.请高人指点,多谢多谢.

------解决方案--------------------
估计是这样:
C# code
curContext.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");

------解决方案--------------------
把curContext.Response.Charset = "Auto"; 改成:
 curContext.Response.Charset = "GB2312";