• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C#导出数据量大于100万【csv】

原作者: [db:作者] 来自: [db:来源] 收藏 邀请
    /// <summary>
    /// Export the data from datatable to CSV file
    /// </summary>
    /// <param name="grid"></param>
    public void ExportDataGridToCSV(System.Data.DataTable dt)
    {
        string strFile = "";
        string path = "";

        //File info initialization
        strFile = "test";
        strFile = strFile + DateTime.Now.ToString("yyyyMMddhhmmss");
        strFile = strFile + ".csv";
        path = Server.MapPath(strFile);



        System.IO.FileStream fs = new FileStream(path, System.IO.FileMode.Create, System.IO.FileAccess.Write);
        StreamWriter sw = new StreamWriter(fs, new System.Text.UnicodeEncoding());
        //Tabel header
        for (int i = 0; i < dt.Columns.Count; i++)
        {
            sw.Write(dt.Columns[i].ColumnName);
            sw.Write("\t");
        }
        sw.WriteLine("");
        //Table body
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            for (int j = 0; j < dt.Columns.Count; j++)
            {
                sw.Write(DelQuota(dt.Rows[i][j].ToString()));
                sw.Write("\t");
            }
            sw.WriteLine("");
        }
        sw.Flush();
        sw.Close();

        DownLoadFile(path);
    }

    private bool DownLoadFile(string _FileName)
    {
        try
        {
            System.IO.FileStream fs = System.IO.File.OpenRead(_FileName);
            byte[] FileData = new byte[fs.Length];
            fs.Read(FileData, 0, (int)fs.Length);
            Response.Clear();
            Response.AddHeader("Content-Type", "application/octet-stream");
            string FileName = System.Web.HttpUtility.UrlEncode(System.Text.Encoding.UTF8.GetBytes(_FileName));
            Response.AddHeader("Content-Disposition", "inline;filename=" + System.Convert.ToChar(34) + FileName + System.Convert.ToChar(34));
            Response.AddHeader("Content-Length", fs.Length.ToString());
            Response.BinaryWrite(FileData);
            fs.Close();
            System.IO.File.Delete(_FileName);
            Response.Flush();
            Response.End();
            return true;
        }
        catch (Exception ex)
        {
            ex.Message.ToString();
            return false;
        }
    }



    /// <summary>
    /// Delete special symbol
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    public string DelQuota(string str)
    {
        string result = str;
        string[] strQuota = { "~", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "`", ";", "'", ",", ".", "/", ":", "/,", "<", ">", "?" };
        for (int i = 0; i < strQuota.Length; i++)
        {
            if (result.IndexOf(strQuota[i]) > -1)
                result = result.Replace(strQuota[i], "");
        }
        return result;
    }

还是.csv靠谱,速度佳。.xls就是个坑货,除非有特殊要求。

//以字符流的形式下载文件
          //以字符流的形式下载文件
            string filePath = HttpContext.Current.Server.MapPath("~/Upload/temp.xls");//路径
            FileStream fs = new FileStream(filePath, FileMode.Open);
            byte[] bytes = new byte[(int)fs.Length];
            fs.Read(bytes, 0, bytes.Length);
            fs.Close();
            //删除文件,看个人喜好
            File.Delete(filePath);
            HttpContext.Current.Response.ContentType = "application/octet-stream";
            //通知浏览器下载文件而不是打开
            HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;  filename=" + HttpUtility.UrlEncode(DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls", System.Text.Encoding.UTF8));
            HttpContext.Current.Response.BinaryWrite(bytes);
            HttpContext.Current.Response.Flush();
            HttpContext.Current.Response.End();

 

直接下载文件 (有个小问题未解决,数据量过大,会在最后出现一段乱码)

        Response.ContentType = "application/octet-stream";
        Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(DateTime.Now.ToString("yyyyMMddHHmmss") + ".csv"));
        string filename = "文件路径";
        Response.TransmitFile(filename);


 分块下载

   System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath);
        if (fileInfo.Exists == true)
        {
            const long ChunkSize = 102400;//100K 每次读取文件,只读取100K,这样可以缓解服务器的压力 
            byte[] buffer = new byte[ChunkSize];
            Response.Clear();
            System.IO.FileStream iStream = System.IO.File.OpenRead(filePath);
            long dataLengthToRead = iStream.Length;//获取下载的文件总大小 
            Response.ContentType = "application/octet-stream";
            Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(DateTime.Now.ToString("yyyyMMddHHmmss") + ".csv"));
            while (dataLengthToRead > 0 && Response.IsClientConnected)
            {
                int lengthRead = iStream.Read(buffer, 0, Convert.ToInt32(ChunkSize));//读取的大小 
                Response.OutputStream.Write(buffer, 0, lengthRead);
                Response.Flush();
                dataLengthToRead = dataLengthToRead - lengthRead;
            }
            Response.Close();
        }

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
I2C详细介绍发布时间:2022-07-13
下一篇:
C#--多线程向同一文件写入发布时间:2022-07-13
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap