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

来源:互联网 发布:2017淘宝蓝海类目 编辑:程序博客网 时间:2024/05/16 16:09
   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;        }

0 0
原创粉丝点击