C#中幾種資料格式儲存xls(DataTable 和List 儲存xls) DataGridView轉DataTable
阿新 • • 發佈:2022-05-30
C#中幾種資料格式儲存xls(DataTable 和List<JObject> 儲存xls)
1.DataTable 儲存xls
/// <summary> /// Datable匯出成Excel,自定義欄位 (NPOI元件) /// </summary> /// <param name="dt"></param> /// <param name="file">匯出路徑(包括檔名與副檔名)</param> /// <param name="nameList">需要匯出指定欄位的對應關係</param> ////生成列的中文對應表 //Hashtable nameList = new Hashtable(); //nameList.Add("ADID", "廣告編碼"); //nameList.Add("ADName", "廣告名稱"); //nameList.Add("year", "年"); public void TableToExcelByCustom(System.Data.DataTable dt, string file, Hashtable nameList) { IWorkbook workbook;string fileExt = Path.GetExtension(file).ToLower(); if (fileExt == ".xlsx") { workbook = new XSSFWorkbook(); } else if (fileExt == ".xls") { workbook = new HSSFWorkbook(); } else { workbook = null; } if (workbook == null) { return; } ISheet sheet = string.IsNullOrEmpty(dt.TableName) ? workbook.CreateSheet("Sheet1") : workbook.CreateSheet(dt.TableName); //表頭 IRow row = sheet.CreateRow(0); int x = 0;//列的序號 for (int i = 0; i < dt.Columns.Count; i++) { //原始方法 //ICell cell = row.CreateCell(i); //cell.SetCellValue(dt.Columns[i].ColumnName); IDictionaryEnumerator Enum = nameList.GetEnumerator(); while (Enum.MoveNext()) { if (Enum.Key.ToString().Trim() == dt.Columns[i].ColumnName) { sheet.SetColumnWidth(x, 20 * 256);//設定列寬 ICell cell = row.CreateCell(x); cell.SetCellValue(Enum.Value.ToString()); x++; } } } //資料 for (int i = 0; i < dt.Rows.Count; i++) { IRow row1 = sheet.CreateRow(i + 1); int y = 0;//列的序號 for (int j = 0; j < dt.Columns.Count; j++) { //原始方法 //ICell cell = row1.CreateCell(j); //cell.SetCellValue(dt.Rows[i][j].ToString()); IDictionaryEnumerator Enum = nameList.GetEnumerator(); while (Enum.MoveNext()) { if (Enum.Key.ToString().Trim() == dt.Columns[j].ColumnName) { ICell cell = row1.CreateCell(y); cell.SetCellValue(dt.Rows[i][j].ToString()); y++; } } } } //轉為位元組陣列 MemoryStream stream = new MemoryStream(); workbook.Write(stream); var buf = stream.ToArray(); //儲存為Excel檔案 using (FileStream fs = new FileStream(file, FileMode.Create, FileAccess.Write)) { fs.Write(buf, 0, buf.Length); fs.Flush(); } }
2.List<JObject> 儲存xls
/// <summary> /// List匯出成Excel,自定義欄位 (NPOI元件) /// </summary> /// <param name="List"></param> /// <param name="file">匯出路徑(包括檔名與副檔名)</param> /// <param name="nameList">需要匯出指定欄位的對應關係</param> ////生成列的中文對應表 //Hashtable nameList = new Hashtable(); //nameList.Add("ADID", "廣告編碼"); //nameList.Add("ADName", "廣告名稱"); //nameList.Add("year", "年"); public void ListToExcel(List<JObject> list, string file, Hashtable nameList) { IWorkbook workbook; string fileExt = Path.GetExtension(file).ToLower(); if (fileExt == ".xlsx") { workbook = new XSSFWorkbook(); } else if (fileExt == ".xls") { workbook = new HSSFWorkbook(); } else { workbook = null; } if (workbook == null) { return; } //ISheet sheet = string.IsNullOrEmpty(dt.TableName) ? workbook.CreateSheet("Sheet1") : workbook.CreateSheet(dt.TableName); ISheet sheet = workbook.CreateSheet("Sheet1"); //表頭 if (list.Count <= 0) return;//空資料返回 StringBuilder columns = new StringBuilder(); JObject listColumns = list[0] as JObject; IRow row = sheet.CreateRow(0); int x = 0;//列的序號 foreach (JToken jkon in listColumns.AsJEnumerable()) { string column = ((JProperty)(jkon)).Name;//列名 IDictionaryEnumerator Enum = nameList.GetEnumerator(); while (Enum.MoveNext()) { if (Enum.Key.ToString().Trim() == column ) { sheet.SetColumnWidth(x, 20 * 256);//設定列寬 ICell cell = row.CreateCell(x); cell.SetCellValue(Enum.Value.ToString()); x++; } } } //資料 for (int i = 0; i < list.Count; i++) { IRow row1 = sheet.CreateRow(i + 1); int y = 0;//列的序號 foreach (JToken jkon in listColumns.AsJEnumerable()) { string column = ((JProperty)(jkon)).Name;//列名 IDictionaryEnumerator Enum = nameList.GetEnumerator(); while (Enum.MoveNext()) { if (Enum.Key.ToString().Trim() == column) { ICell cell = row1.CreateCell(y); cell.SetCellValue(list[i][column].ToString()); y++; } } } } //轉為位元組陣列 MemoryStream stream = new MemoryStream(); workbook.Write(stream); var buf = stream.ToArray(); //儲存為Excel檔案 using (FileStream fs = new FileStream(file, FileMode.Create, FileAccess.Write)) { fs.Write(buf, 0, buf.Length); fs.Flush(); } }
=======
要使用上面兩個方法,就必須把資料轉成上面指定的格式(DataTable 和List)
1. DataGridView轉DataTable
//先判斷DataGridView不能為空 //===DataGridView轉DataTable(開始) DataTable dt = new DataTable();
//表頭 for (int count = 0; count < dgv.Columns.Count; count++) { DataColumn dc = new DataColumn(dgv.Columns[count].Name.ToString()); dt.Columns.Add(dc); }
//新增資料 for (int count = 0; count < dgv.RowCount; count++) { DataRow dr = dt.NewRow(); for (int countsub = 0; countsub < dgv.Columns.Count; countsub++) { dr[countsub] = Convert.ToString(dgv.Rows[count].Cells[countsub].Value); } dt.Rows.Add(dr); } //===DataGridView轉DataTable(結束)
2.List<JObject>轉DataTable (List可以直接存,也可以轉成DataTable)
//先要判斷List,不能為空 list是 List<JObject> list = new List<JObject>(); 這樣的資料(或是接受的介面json資料)
//=== List<JObject>轉DataTable(開始) DataTable dt = new DataTable(); //把List<JObject>資料,轉成DataTable StringBuilder columns = new StringBuilder(); JObject listColumns = list[0] as JObject;
//構造表頭 foreach (JToken jkon in listColumns.AsJEnumerable()) { string column_name = ((JProperty)(jkon)).Name; DataColumn dc = new DataColumn(column_name); dt.Columns.Add(dc); } //新增資料 for (int count = 0; count < list.Count; count++) { DataRow dr = dt.NewRow(); foreach (JToken jkon in listColumns.AsJEnumerable()) { string column_name = ((JProperty)(jkon)).Name; dr[column_name] = Convert.ToString(list[count][column_name].ToString()); } dt.Rows.Add(dr); } //=== List<JObject>轉DataTable(結束)
參考: https://www.csdn.net/tags/MtTaEgxsMDIwODA1LWJsb2cO0O0O.html