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

    /// <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();
        }

 

posted @ 2017-02-16 15:28  哈佛  阅读(4857)  评论(0编辑  收藏  举报