• C#导出csv文件 支持中文的解决方案


            #region 导出CSV下载
            string exportFileName = "Export" + DateTime.Now.ToString("yyyyMMddHHmmss");
            System.Web.HttpContext context = System.Web.HttpContext.Current;
            StringBuilder sb = new StringBuilder();
            sb.Append("FirstName,LastName,PhoneNo.,State,TimeZone,ZipCode
    ");
            for (int i = 0; i < result.PhoneList.Count; i++)
            {
                sb.Append(result.PhoneList[i].FirstName + "," + result.PhoneList[i].LastName + "," + result.PhoneList[i].Phone + "," + result.PhoneList[i].State + "," + result.PhoneList[i].TimeZone + "," + result.PhoneList[i].ZipCode + "
    ");
            }
            StringWriter sw = new StringWriter(sb);
            sw.Close();
            context.Response.Clear();
            /* 
             * Acme 2012-07-04 edit 
             *  
            context.Response.Charset = "gb2312"; 
            context.Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312"); 
            context.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; // "application/octet-stream"; //"application/vnd.ms-excel"; //application/vnd.openxmlformats-officedocument.spreadsheetml.sheet                   
            //context.Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", fileName)); 
            */
            //below is new writing  
            context.Response.Charset = "UTF-8";
            context.Response.ContentEncoding = System.Text.Encoding.UTF8;
            context.Response.HeaderEncoding = System.Text.Encoding.UTF8;
            context.Response.ContentType = "text/csv";
            //主要是下面这一句
            context.Response.BinaryWrite(new byte[] { 0xEF, 0xBB, 0xBF });
            context.Response.Write(sw);
            context.Response.AppendHeader("content-disposition", "attachment; filename=" + HttpUtility.UrlEncode(exportFileName + ".csv", System.Text.Encoding.UTF8).Replace("+", "%20"));
            //context.Response.OutputStream.Write(fileData, 0, fileData.Length);  
            context.Response.Flush();
            context.Response.End();
            #endregion
  • 相关阅读:
    Grandpa's Estate
    The Fortified Forest
    Scrambled Polygon
    Wall
    激情的大三
    无聊的大二
    美好的大一
    高精度 加减乘
    Erasing Edges
    git放弃修改&放弃增加文件
  • 原文地址:https://www.cnblogs.com/zhangsir/p/3488935.html
Copyright © 2020-2023  润新知