用输出流导出EXCEL,在2007下打开乱码问题

该方法试用与2003与2007,可以导出多个SHEET.不会有乱码.具体如下:

  System.IO.StringWriter sw = new System.IO.StringWriter();
   System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(sw);
   this.repPrj.RenderControl(hw);  //repPrj为Control的ID,经过我的实验,Control可以为自定义控件,服务器端控件,客户端控件.

string[] strHTML = {sw.ToString()};//为数组,如果想导出多个SHEET;则用上面的方法做多个输出流.
string[] strSheetNames = {};//每个SHEET的名字,支持中文.

string fileName;

ExportToExcelInMIME(this.Response,fileName,strHTML,strSheetNames);

public static void ExportToExcelInMIME(HttpResponse rs,string fileName,string[] strHtmls,string[] strSheetsName)
  {
   rs.ContentType = "application/vnd.ms-excel";
   rs.Charset = "utf-8";
   rs.ContentEncoding = System.Text.Encoding.UTF8 ;
   string name = HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8);//如有乱码,可以调试该处的编码格式
   rs.AppendHeader("Content-Disposition", "inline;filename=" + name + ".xls");
   strSheetsName = StrToASC(strSheetsName).Split(',');
   string strResult = CreateExcel(strHtmls,strSheetsName);
   rs.Write(strResult.ToString().Replace("<a href=# ", "<p "));
   rs.End();
  }

public static string CreateExcel(string[] strHtmls,string[] strSheetsName)
  {
   string strResult = "";
   strResult = CreateExcelHead(strSheetsName);
   for(int i=0 ; i<strSheetsName.Length ; i++)
   {
    strResult += CreateExcelBoundary(strHtmls[i],i.ToString());
   }
   strResult += "--"+ SysConsts.Boundary +"--";

   return strResult;
  }

 public static string CreateExcelHead(string[] strSheetsName)
  {
   StringBuilder sb = new StringBuilder();
   sb.Append("MIME-Version: ");
   sb.Append(SysConsts.MIMEVersion);
   sb.Append("/r/nX-Document-Type: ");
   sb.Append(SysConsts.DocumentType);
   sb.Append("/r/nContent-Type: ");
   sb.Append(SysConsts.ContentType);
   sb.Append("; boundary=/"");
   sb.Append(SysConsts.Boundary);
   sb.Append("/"/r/n");
   sb.Append("/r/n");
   sb.Append("------BOUNDARY_9527----/r/n");
   sb.Append("Content-Location: file:///C:/0E8D990C/MimeExcel.xml/r/n");
   sb.Append("Content-Transfer-Encoding: quoted-printable/r/n");
   sb.Append("Content-Type: text/html; charset=/"us-ascii/"/r/n");
   sb.Append("/r/n");
   sb.Append("/r/n<html xmlns:o=3D/"urn:schemas-microsoft-com:office:office/"/r/n");
   sb.Append("xmlns:x=3D/"urn:schemas-microsoft-com:office:excel/"/r/n");
   sb.Append("xmlns=3D/"http://www.w3.org/TR/REC-html40/">/r/n");
   sb.Append("<head>/r/n");
   sb.Append("<xml>/r/n");
   sb.Append("<x:ExcelWorkbook>/r/n");
   sb.Append(" <x:ExcelWorksheets>/r/n");

   for(int i=0 ; i<strSheetsName.Length ; i++)
   {
    sb.Append("  <x:ExcelWorksheet>/r/n");
    sb.Append("   <x:Name>").Append(strSheetsName[i].ToString()).Append("</x:Name>/r/n");
    sb.Append("   <x:WorksheetSource HRef=3D/"cid:sheet").Append(i.ToString()).Append("/"/>/r/n");
    sb.Append("  </x:ExcelWorksheet>/r/n");
   }

   sb.Append(" </x:ExcelWorksheets>/r/n");
   sb.Append("</x:ExcelWorkbook>/r/n");
   sb.Append("</xml>/r/n");
   sb.Append("</head>/r/n");
   sb.Append("</html>/r/n");

   return sb.ToString();
  }

  public static string CreateExcelBoundary(string strHtml,string strSheetName)
  {
   StringBuilder sb = new StringBuilder();
   sb.Append("/r/n--").Append(SysConsts.Boundary).Append("/r/n");
   sb.Append("Content-ID: sheet").Append(strSheetName).Append("/r/n");
   sb.Append("Content-Transfer-Encoding: utf-8/r/n");//如有乱码,可以调试该处的编码格式
   sb.Append("Content-Type: text/html; charset=/"utf-8/"/r/n");//如有乱码,可以调试该处的编码格式
   sb.Append("/r/n");
   sb.Append("<html xmlns:o=3D/"urn:schemas-microsoft-com:office:office/"/r/n");
   sb.Append("xmlns:x=3D/"urn:schemas-microsoft-com:office:excel/"/r/n");
   sb.Append("xmlns=3D/"http://www.w3.org/TR/REC-html40/">/r/n");
   sb.Append("<head>/r/n");
   sb.Append("<xml>/r/n");
   sb.Append(" <x:WorksheetOptions>/r/n");
   sb.Append("  <x:ProtectContents>False</x:ProtectContents>/r/n");
   sb.Append("  <x:ProtectObjects>False</x:ProtectObjects>/r/n");
   sb.Append("  <x:ProtectScenarios>False</x:ProtectScenarios>/r/n");
   sb.Append(" </x:WorksheetOptions>/r/n");
   sb.Append("</xml>/r/n");
   sb.Append("</head>/r/n");
   sb.Append("<body>/r/n");
   sb.Append ("<meta http-equiv=Content-Type content=text/html;charset=utf-8>");
   sb.Append(strHtml);
   sb.Append("/r/n</body>/r/n");
   sb.Append("</html>/r/n");
   //   sb.Append("------BOUNDARY_9527------/r/n");

   return sb.ToString();
  }

 

/// <summary>
  /// 将字符串转换为asc码
  /// </summary>
  /// <param name="rs"></param>
  /// <param name="grid"></param>
  /// <param name="fileName"></param>
  public static string StrToASC(string str)
  {
   string acs = " ";
   foreach(char a in str)
   {
    int i = (int)a;
    acs += "&#"+i.ToString()+";";
   }
   return acs;
  }
  /// <summary>
  /// 将字符串数组转换为asc码
  /// </summary>
  /// <param name="rs"></param>
  /// <param name="grid"></param>
  /// <param name="fileName"></param>
  public static string StrToASC(string [] str)
  {
   string str1 = "";
   foreach(string a in str)
   {
    str1 += StrToASC(a)+",";
   }
   str1 = str1.TrimEnd(',');
   return str1;
  }

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
### 回答1: 在使用 Python 导出 CSV 文件时,如果在 Excel打开显示乱码,可能是因为 Excel 无法识别 CSV 文件的编码格式。 解决方法有以下几种: 1. 使用 Python 的 `codecs` 库进行编码转换,将 CSV 文件从原来的编码转换为 UTF-8 编码,然后再用 Excel 打开。 2. 在 Excel 中使用「数据」选项卡中的「获取外部数据」按钮,选择「从文本」选项,然后手动选择 CSV 文件的编码格式。 3. 使用文本编辑器(如 Notepad++)打开 CSV 文件,然后将其转换为 UTF-8 编码,再用 Excel 打开。 希望以上内容能帮助到你! ### 回答2: 当使用Python导出CSV文件,并用Excel打开时出现乱码问题,可以尝试以下解决方法。 1. 指定CSV文件的编码格式:在导出CSV文件时,可以使用`encoding`参数指定文件的编码格式。例如,可以使用UTF-8编码格式来导出CSV文件,以确保兼容性。 2. 使用Excel打开时选择正确的编码格式:在Excel打开CSV文件时,可以选择正确的编码格式来避免乱码问题。在打开文件时,选择正确的编码格式,如UTF-8,以确保文本正确显示。 3. 使用文本导入向导打开CSV文件:在Excel的“数据”选项卡下,选择“从文本”功能打开CSV文件。这样做可以通过导入向导指定正确的编码格式和分隔符,以确保数据正确显示。 4. 使用其他软件或编辑器打开CSV文件:如果Excel仍然无法正确显示CSV文件,可以尝试使用其他软件或文本编辑器打开。例如,可以使用记事本、Sublime Text、Notepad++等文本编辑器,或者其他电子表格软件如Google Sheets来打开CSV文件,然后再尝试将其导入Excel。 通过以上方法,希望能够解决Python导出CSV文件Excel乱码问题,并正确显示CSV文件中的文本内容。 ### 回答3: 当使用Python导出CSV文件并使用Excel打开时出现乱码问题通常是由于文件编码的原因。在Python中,CSV文件的默认编码为UTF-8,而Excel默认使用的是ANSI编码。这种编码不匹配可能导致乱码问题。 解决这个问题有以下几种方法: 1. 使用Excel打开CSV文件之前,可以先将文件的编码转换为Excel所支持的编码,如GB2312。可以使用Python的`codecs`模块来实现编码转换,例如: ```python import codecs # 读取UTF-8编码的CSV文件 with codecs.open('data.csv', 'r', 'utf-8') as f: content = f.read() # 将编码转换为GB2312并保存为新的CSV文件 with codecs.open('data_ansi.csv', 'w', 'gb2312') as f: f.write(content) ``` 2. 使用Python的`pandas`库来导出CSV文件,它有更好的编码处理能力。在写入CSV文件时,可以指定编码为ANSI,例如: ```python import pandas as pd # 将DataFrame写入CSV文件,并指定编码为ANSI df.to_csv('data.csv', encoding='ansi', index=False) ``` 使用这些方法之一,可以避免在使用Excel打开导出的CSV文件时出现乱码问题
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值