当前位置: 代码迷 >> ASP.NET >> 生成.csv文件给用户上载
  详细解决方案

生成.csv文件给用户上载

热度:10310   发布时间:2013-02-25 00:00:00.0
生成.csv文件给用户下载
求解,,谁知道Asp.net 生成.csv文件给用户下载,而且 用excel 打开不乱码? 我找了个方法但肜excel打开会乱码~
asp.net

------解决方案--------------------------------------------------------
Response.Clear();
            Response.Charset = "UTF-8";
            Response.ContentEncoding = System.Text.Encoding.UTF8;
            Response.HeaderEncoding = System.Text.Encoding.UTF8;
            Response.ContentType = "text/csv";
            Response.BinaryWrite(new byte[] { 0xEF, 0xBB, 0xBF }); //这句是重点哦,不乱码的保证
            Response.AddHeader("Content-Disposition", string.Format("attachment;filename=Customer{0:yyyy-MM-dd}.csv;", DateTime.Now));



按上面的写,保证不乱码,结贴吧
------解决方案--------------------------------------------------------
System.Text.StringBuilder sb = new System.Text.StringBuilder();

//sb 中定义生成.csv文件的格式 中间以"\t"分开

 Response.AddHeader("Content-Disposition", "attachment; filename=vhost" + string.Format("{0:yyyyMMddhhmmss}", DateTime.Now) + ".xls");
        Response.ContentType = "application/text";
        Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
        Response.Write(sb);
        Response.End();



//convert the dataset to CSV
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < this.GridViewSearchResult.Columns.Count; i++)
            {
                if (this.GridViewSearchResult.Columns[i].Visible)
                {
                    sb.Append(@"""" + this.GridViewSearchResult.Columns[i].HeaderText + @"""" + ",");
                }
            }
            sb.Append("\n");
            foreach (DataRow row in ds.Tables[0].Rows)
            {
                for (int j = 0; j < this.GridViewSearchResult.Columns.Count;j++ )
                {
                    sb.Append(@""""+row[this.GridViewSearchResult.Columns[j].HeaderText ].ToString().Replace(@"""",@"""""")+  @"""" + ",");
  相关解决方案