C#導出Excel,Csv


相信大家經常接觸導出了,這邊本人就記錄下導出的方法以便后面回顧.

xls支持6萬條數據

xlsx支持100萬條數據 

CSV可以用記事本打開可以用excel打開

  1 using NPOI;
  2 using NPOI.OpenXml4Net;
  3 using NPOI.OpenXmlFormats;
  4 using NPOI.SS.UserModel;
  5 using NPOI.HSSF.UserModel;
  6 using NPOI.XSSF.UserModel;
  7 using NPOI.HSSF.Util;
  8 
  9         /// <summary>
 10         /// DataTable生成到excel(目前僅支持2維列表導出)
 11         /// </summary>
 12         /// <param name="source">數據集</param>
 13         /// <param name="fullPath"></param>
 14         /// <returns></returns>
 15         public static void DataTableExportExcel(DataTable source, string fullPath)
 16         {
 17             try
 18             {
 19                 int index = fullPath.LastIndexOf('.');
 20                 string extension = fullPath.Substring(index);
 21                 IWorkbook workBook = null;
 22                 if (extension == ".xls")
 23                 {
 24                     workBook = new HSSFWorkbook();
 25                 }
 26                 if (extension == ".xlsx")
 27                 {
 28                     workBook = new XSSFWorkbook();
 29                 }
 30                 ISheet sheet = workBook.CreateSheet("Sheet1");
 31                 IRow headRow = sheet.CreateRow(0);
 32 
 33                 headRow.HeightInPoints = 20;//設置表頭高度
 34                 ICellStyle cellStyle = workBook.CreateCellStyle();
 35                 cellStyle.Alignment = HorizontalAlignment.Center;
 36                 cellStyle.VerticalAlignment = VerticalAlignment.Center;
 37                 cellStyle.FillPattern = FillPattern.SolidForeground;
 38                 cellStyle.BorderBottom = BorderStyle.Thin;
 39                 cellStyle.BorderLeft = BorderStyle.Thin;
 40                 cellStyle.BorderRight = BorderStyle.Thin;
 41                 cellStyle.BorderTop = BorderStyle.Thin;
 42                 cellStyle.FillForegroundColor = HSSFColor.Grey25Percent.Index;
 43                 for (int i = 0; i < source.Columns.Count; i++)//生成表頭
 44                 {
 45                     headRow.CreateCell(i).SetCellValue(source.Columns[i].ColumnName);
 46                     sheet.SetColumnWidth(i, (source.Columns[i].ColumnName.Length * 3) * 256);
 47                     headRow.GetCell(i).CellStyle = cellStyle;
 48                 }
 49                 IRow row = null;
 50                 ICellStyle cellStyleRow = workBook.CreateCellStyle();
 51                 cellStyleRow.Alignment = HorizontalAlignment.Center;
 52                 cellStyleRow.VerticalAlignment = VerticalAlignment.Center;
 53                 cellStyleRow.FillPattern = FillPattern.SolidForeground;
 54                 cellStyleRow.BorderBottom = BorderStyle.Thin;
 55                 cellStyleRow.BorderLeft = BorderStyle.Thin;
 56                 cellStyleRow.BorderRight = BorderStyle.Thin;
 57                 cellStyleRow.BorderTop = BorderStyle.Thin;
 58                 cellStyleRow.FillForegroundColor = HSSFColor.White.Index;
 59                 for (int i = 0; i < source.Rows.Count; i++)//生成數據體
 60                 {
 61                     row = sheet.CreateRow(i + 1);
 62                     for (int j = 0; j < source.Columns.Count; j++)
 63                     {
 64                         row.CreateCell(j).SetCellValue(source.Rows[i][j] == null ? "" : source.Rows[i][j].ToString());
 65                         row.GetCell(j).CellStyle = cellStyleRow;
 66                     }
 67                 }
 68                 using (FileStream stream = File.OpenWrite(fullPath))
 69                 {
 70                     workBook.Write(stream);
 71                 }
 72             }
 73             catch (Exception ex)
 74             {
 75                 throw new Exception("生成excel異常數據出錯," + ex.Message);
 76             }
 77         }
 78 
 79 
 80 
 81 
 82         /// <summary>
 83         /// 寫入CSV
 84         /// </summary>
 85         /// <param name="fileName">文件名</param>
 86         /// <param name="dt">要寫入的datatable</param>
 87         public static void WriteCSV(string fileName, DataTable dt)
 88         {
 89             FileStream fs;
 90             StreamWriter sw;
 91 
 92 
 93             string data = null;
 94 
 95             //判斷文件是否存在,存在就不再次寫入列名
 96             if (!File.Exists(fileName))
 97             {
 98                 fs = new FileStream(fileName, FileMode.Create, FileAccess.Write);
 99                 sw = new StreamWriter(fs, Encoding.UTF8);
100 
101                 //寫出列名稱
102                 for (int i = 0; i < dt.Columns.Count; i++)
103                 {
104                     data += dt.Columns[i].ColumnName.ToString();
105                     if (i < dt.Columns.Count - 1)
106                     {
107                         data += ",";//中間用,隔開
108                     }
109                 }
110                 sw.WriteLine(data);
111             }
112             else
113             {
114                 fs = new FileStream(fileName, FileMode.Append, FileAccess.Write);
115                 sw = new StreamWriter(fs, Encoding.UTF8);
116             }
117 
118             //寫出各行數據
119             for (int i = 0; i < dt.Rows.Count; i++)
120             {
121                 data = null;
122                 for (int j = 0; j < dt.Columns.Count; j++)
123                 {
124                     data += dt.Rows[i][j].ToString();
125                     if (j < dt.Columns.Count - 1)
126                     {
127                         data += "\t" + ",";//中間用,隔開 這里加入\t是因為 導出excle時會把數字長度超過會科學計數法顯示
128                     }
129                 }
130                 sw.WriteLine(data);
131             }
132             sw.Close();
133             fs.Close();
134         }


主要是引用的NPOI 導入導出都有 這邊只記錄了導出

方法比較簡單,傳入一個查詢出的DT數據集,和路徑 路徑一般都是配置在Web.config里面讀取

1 <configuration>
2   <appSettings>
3     <add key="ExportPath" value="DownloadExcels" />
4   </appSettings>
5 </configuration>

讀取config配置

string path=this.Server.MapPath("/" + System.Configuration.ConfigurationManager.AppSettings["ExportPath"]);

this.Server.MapPath //應用程序根目錄所在的位置

導出方法里面代碼如下:

try
                {
                    //string suffix = ".xls";
                    string suffix = ".csv";
                    string FILE_NAME = DateTime.Now.ToString("yyyyMMddHHmm");
                    //避免傳入中文時出現亂碼,將傳過來的值轉成UTF-8
                    FILE_NAME = System.Web.HttpUtility.UrlDecode(FILE_NAME, System.Text.Encoding.UTF8);

                    string exportPath = QM.path; //導出文件路徑

                    if (!Directory.Exists(exportPath))
                    {
                        Directory.CreateDirectory(exportPath);
                    }
                    string fullFileName = exportPath + "//" + FILE_NAME + suffix;

                    //DataTableExportExcel(dt, fullFileName);

                    WriteCSV(fullFileName, dt);

                    json.Data = "/" + ConfigurationManager.AppSettings["ExportPath"] + "/" + FILE_NAME + suffix;
                }
View Code

 

 
        

 

這里JSON.Data最后就會形成一個路徑

 1     //導出按鈕
 2     function Getexport() {
 3         $.ajax({
 4             type: 'POST',
 5             url: "/Home/GetExport",
 6             data: {11             },
12             dataType: 'json',
13             success: function (res) {
14                 var json = jQuery.parseJSON(res);
15                 if (json.Success) {
16                     var downError = document.createElement("A");
17                     downError.href = json.Data;
18                     document.body.appendChild(downError);
19                     downError.click();
20                 }
21                 else {
22                     alert("信息提示導出數據出錯," + json.Message);
23                 }
24             }
25         });
26     }

 

 第一次寫 也不知道怎么排版 大家見諒!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM