C# DataTable 导出CSV 文件并在客户端下载

   public static bool ExportToCSV(System.Data.DataTable dt)
        {
            string strLine = "";
            string pathFile = String.Format("{0}{1}.csv", HttpContext.Current.Server.MapPath("Excel/"), "客户列表");//文件保存路径及名称
            FileInfo fi = new FileInfo(pathFile);//判断文件是否存在,若存在则删除
            if (fi.Exists)
            {
                fi.Delete();
            }
            StreamWriter sw;
            try
            {
                sw = new StreamWriter(pathFile, false, System.Text.Encoding.GetEncoding(-0)); //覆盖
                //表头
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    if (i > 0)
                        strLine += ",";
                    strLine += dt.Columns[i].ColumnName;
                }
                strLine.Remove(strLine.Length - 1);
                sw.WriteLine(strLine);
                strLine = "";
                //表的内容
                for (int j = 0; j < dt.Rows.Count; j++)
                {
                    strLine = "";
                    int colCount = dt.Columns.Count;
                    for (int k = 0; k < colCount; k++)
                    {
                        if (k > 0 && k < colCount)
                            strLine += ",";
                        if (dt.Rows[j][k] == null)
                            strLine += "";
                        else
                        {
                            string cell ="'"+ dt.Rows[j][k].ToString().Trim();//前面加的单引号则是防止数字被转换成其它格式
                            //防止里面含有特殊符号
                            cell = cell.Replace("\"", "\"\"");
                            cell = "\"" + cell + "\"";
                            strLine += cell;
                        }
                    }
                    sw.WriteLine(strLine);
                }
                sw.Close();
                HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpContext.Current.Server.UrlEncode(pathFile));
                HttpContext.Current.Response.ContentType = "application/ms-excel";// 指定返回的是一个不能被客户端读取的流,必须被下载
                HttpContext.Current.Response.WriteFile(pathFile); // 把文件流发送到客户端
                HttpContext.Current.Response.End();
                string msg = "数据被成功导出到:" + pathFile;
                Console.WriteLine(msg);
            }
            catch (Exception ex)
            {
                string msg = "导出错误:" + pathFile;
                Console.WriteLine(msg);
                return false;
            }
            return true;
        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值