在導出大量CSV數據的時候,經常體積較大,採用C#自帶的壓縮類,能夠方便的實現該功能,而且壓縮比例很高,該方法在個人開源工具DataPie中已經通過實踐檢驗。個人上一篇博客《功能齊全、效率一流的免費開源數據庫導入導出工具(c#開發,支持SQL server、SQLite、ACCESS三種數據庫),每個月藉此處理數據5G以上》中有該工具的完整源碼,有須要的同窗能夠看看。html
在.net 4.5中,能夠輕鬆建立zip文件 ,首先須要引入 System.IO.Compression.dll、System.IO.Compression.FileSystem.dll兩個文件。其中ZipArchive 類表示一些壓縮使用 Zip 文件格式的文件。ZipArchiveEntry 類表示單個 ZipArchive。ZipArchive 一般包含一個或多個 ZipArchiveEntry 實例。數據庫
DataPie中實現csv文件壓縮導出的主要代碼以下:c#
using System; using System.Linq; using System.Text; using System.IO.Compression; using System.Data; using System.Diagnostics; using System.IO; namespace DataPie.Core { public class DBToZip { public static int DataReaderToZip(String zipFileName, IDataReader reader, string tablename) { Stopwatch watch = Stopwatch.StartNew(); watch.Start(); using (FileStream fsOutput = new FileStream(zipFileName, FileMode.OpenOrCreate, FileAccess.ReadWrite)) { using (ZipArchive archive = new ZipArchive(fsOutput, ZipArchiveMode.Update)) { ZipArchiveEntry readmeEntry = archive.CreateEntry(tablename + ".csv"); using (StreamWriter writer = new StreamWriter(readmeEntry.Open(), Encoding.UTF8)) { for (int i = 0; i < reader.FieldCount; i++) { if (i > 0) writer.Write(','); writer.Write(reader.GetName(i) ); } writer.Write(Environment.NewLine); while (reader.Read()) { for (int i = 0; i < reader.FieldCount; i++) { if (i > 0) writer.Write(','); String v = reader[i].ToString(); if (v.Contains(',') || v.Contains('\n') || v.Contains('\r') || v.Contains('"')) { writer.Write('"'); writer.Write(v.Replace("\"", "\"\"")); writer.Write('"'); } else { writer.Write(v); } } writer.Write(Environment.NewLine); } } } } watch.Stop(); return Convert.ToInt32(watch.ElapsedMilliseconds / 1000); } } }