1.csv相关
1 public static class CsvHelper 2 { 3 /// <summary> 4 /// 根据csv路径获取datatable 5 /// </summary> 6 /// <param name="csvPath"></param> 7 /// <param name="errMsg"></param> 8 /// <returns></returns> 9 public static DataTable GetDataTable(string csvPath, out string errMsg) 10 { 11 var result = GetDt(csvPath, out errMsg, true); 12 GC.Collect(); 13 GC.WaitForPendingFinalizers(); 14 GC.Collect(); 15 GC.WaitForPendingFinalizers(); 16 return result; 17 } 18 private static DataTable GetDt(string csvPath, out string errMsg, bool hasTitle = false) 19 { 20 var dt = new DataTable(); 21 try 22 { 23 //将数据读入到DataTable中 24 if (!File.Exists(csvPath)) 25 { 26 errMsg = "找不到csv文件" + csvPath; 27 return null; 28 } 29 using (StreamReader sr = new StreamReader(csvPath)) 30 { 31 string line = sr.ReadLine(); 32 if (!string.IsNullOrEmpty(line)) 33 { 34 var columes = line.Split(','); 35 //生成列头 36 for (var i = 0; i < columes.Length; i++) 37 { 38 var name = "column" + i; 39 if (hasTitle) 40 { 41 var txt = columes[i]; 42 if (!string.IsNullOrWhiteSpace(txt)) 43 { 44 name = txt; 45 } 46 } 47 while (dt.Columns.Contains(name)) name = name + "_1"; //重复行名称会报错。 48 dt.Columns.Add(new DataColumn(name, typeof(string))); 49 } 50 51 if (!hasTitle) 52 { 53 var dr = dt.NewRow(); 54 for (var iCol = 0; iCol < columes.Length; iCol++) 55 { 56 var range = columes[iCol]; 57 dr[iCol] = range; 58 } 59 dt.Rows.Add(dr); 60 } 61 line = sr.ReadLine(); 62 //生成行数据 63 while (!string.IsNullOrWhiteSpace(line)) 64 { 65 columes = line.Split(','); 66 var dr = dt.NewRow(); 67 for (var iCol = 0; iCol < columes.Length; iCol++) 68 { 69 var range = columes[iCol]; 70 dr[iCol] = range; 71 } 72 dt.Rows.Add(dr); 73 line = sr.ReadLine(); 74 } 75 } 76 } 77 errMsg = ""; 78 return dt; 79 } 80 catch (Exception ex) 81 { 82 LogHelper.Log(ex); 83 errMsg = ex.Message; 84 return null; 85 } 86 } 87 88 /// <summary> 89 /// 将dataTable保存到csv文件 90 /// </summary> 91 /// <param name="dt"></param> 92 /// <param name="csvPath"></param> 93 /// <param name="errMsg"></param> 94 /// <returns></returns> 95 public static bool SaveDataTable(DataTable dt, string csvPath, out string errMsg) 96 { 97 var result = SaveDt(dt, csvPath, out errMsg); 98 GC.Collect(); 99 GC.WaitForPendingFinalizers(); 100 GC.Collect(); 101 GC.WaitForPendingFinalizers(); 102 return result; 103 } 104 105 private static bool SaveDt(DataTable dt, string csvPath, out string errMsg) 106 { 107 try 108 { 109 //将数据读入到DataTable中 110 using (StreamWriter sr = new StreamWriter(csvPath, false, Encoding.Default)) 111 { 112 var iRowCount = dt.Rows.Count; 113 var iColCount = dt.Columns.Count; 114 //生成列头 115 StringBuilder firstRow = new StringBuilder(); 116 for (var i = 0; i < iColCount; i++) 117 { 118 firstRow.Append(dt.Columns[i].ColumnName + ","); 119 } 120 sr.WriteLine(firstRow.ToString().TrimEnd(',')); 121 for (var iRow = 0; iRow < iRowCount; iRow++) 122 { 123 StringBuilder otherRow = new StringBuilder(); 124 for (var iCol = 0; iCol < iColCount; iCol++) 125 { 126 otherRow.Append(dt.Rows[iRow][iCol] + ","); 127 } 128 sr.WriteLine(otherRow.ToString().TrimEnd(',')); 129 } 130 errMsg = ""; 131 return true; 132 } 133 } 134 catch (Exception ex) 135 { 136 LogHelper.Log(ex); 137 errMsg = ex.Message; 138 return false; 139 } 140 } 141 }
2.datatable相关
1 public class DataTableHelper 2 { 3 4 /// <summary> 5 /// DataTable转化为List集合 6 /// </summary> 7 /// <typeparam name="T">实体对象</typeparam> 8 /// <param name="dt">datatable表</param> 9 /// <returns>返回list集合</returns> 10 public static List<T> TableToList<T>(DataTable dt ) 11 { 12 List<T> list = new List<T>(); 13 Type type = typeof(T); 14 foreach (DataRow row in dt.Rows) 15 { 16 PropertyInfo[] pArray = type.GetProperties(); //集合属性数组 17 T entity = Activator.CreateInstance<T>(); //新建对象实例 18 foreach (PropertyInfo p in pArray) 19 { 20 if (!dt.Columns.Contains(p.Name) || row[p.Name] == null || row[p.Name] == DBNull.Value) 21 { 22 continue; //DataTable列中不存在集合属性或者字段内容为空则,跳出循环,进行下个循环 23 } 24 try 25 { 26 var obj = Convert.ChangeType(row[p.Name], p.PropertyType);//类型强转,将table字段类型转为集合字段类型 27 p.SetValue(entity, obj, null); 28 } 29 catch (Exception) 30 { 31 32 } 33 } 34 list.Add(entity); 35 } 36 return list; 37 } 38 39 40 /// <summary> 41 /// List集合转DataTable 42 /// </summary> 43 /// <typeparam name="T">实体类型</typeparam> 44 /// <param name="list">传入集合</param> 45 /// <returns>返回datatable结果</returns> 46 public static DataTable ListToTable<T>(List<T> list ) 47 { 48 Type tp = typeof(T); 49 PropertyInfo[] proInfos = tp.GetProperties(); 50 DataTable dt = new DataTable(); 51 foreach (var item in proInfos) 52 { 53 dt.Columns.Add(item.Name, typeof(string)); //添加列明及对应类型 54 } 55 foreach (var item in list) 56 { 57 DataRow dr = dt.NewRow(); 58 foreach (var proInfo in proInfos) 59 { 60 object obj = proInfo.GetValue(item,null); 61 if (obj == null) 62 { 63 continue; 64 } 65 if ( proInfo.PropertyType == typeof(DateTime) && Convert.ToDateTime(obj) < Convert.ToDateTime("1753-01-01")) 66 { 67 continue; 68 } 69 dr[proInfo.Name] = obj; 70 } 71 dt.Rows.Add(dr); 72 } 73 return dt; 74 } 75 }
3.excel相关
1 public static class ExcelHelper 2 { 3 /// <summary> 4 /// 根据excel路径获取datatable 5 /// </summary> 6 /// <param name="excelPath"></param> 7 /// <param name="errMsg"></param> 8 /// <returns></returns> 9 public static DataTable GetDataTable(string excelPath, out string errMsg) 10 { 11 var result = GetDt(excelPath, out errMsg, true); 12 GC.Collect(); 13 GC.WaitForPendingFinalizers(); 14 GC.Collect(); 15 GC.WaitForPendingFinalizers(); 16 return result; 17 } 18 private static DataTable GetDt(string excelFilePath, out string errMsg, bool hasTitle = false) 19 { 20 Microsoft.Office.Interop.Excel.Application app = null; 21 Microsoft.Office.Interop.Excel._Workbook workbook = null; 22 var dt = new DataTable(); 23 object oMissiong = System.Reflection.Missing.Value; 24 try 25 { 26 app = new Microsoft.Office.Interop.Excel.Application(); 27 28 workbook = app.Workbooks.Open(excelFilePath, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, 29 oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong); 30 var sheets = workbook.Worksheets; 31 32 //将数据读入到DataTable中 33 var worksheet = (Microsoft.Office.Interop.Excel.Worksheet)sheets.Item[1]; //读取第一张表 34 if (worksheet == null) 35 { 36 errMsg = "打开excel失败,请确保excel安装环境正确"; 37 return null; 38 } 39 40 var iRowCount = worksheet.UsedRange.Rows.Count; 41 var iColCount = worksheet.UsedRange.Columns.Count; 42 //生成列头 43 for (var i = 0; i < iColCount; i++) 44 { 45 var name = "column" + i; 46 if (hasTitle) 47 { 48 var txt = ((Microsoft.Office.Interop.Excel.Range)worksheet.Cells[1, i + 1]).Text.ToString(); 49 if (!string.IsNullOrWhiteSpace(txt)) name = txt; 50 } 51 while (dt.Columns.Contains(name)) name = name + "_1"; //重复行名称会报错。 52 dt.Columns.Add(new DataColumn(name, typeof(string))); 53 } 54 //生成行数据 55 var rowIdx = hasTitle ? 2 : 1; 56 for (var iRow = rowIdx; iRow <= iRowCount; iRow++) 57 { 58 var dr = dt.NewRow(); 59 for (var iCol = 1; iCol <= iColCount; iCol++) 60 { 61 var range = (Microsoft.Office.Interop.Excel.Range)worksheet.Cells[iRow, iCol]; 62 dr[iCol - 1] = (range.Value2 == null) ? "" : range.Text.ToString(); 63 } 64 dt.Rows.Add(dr); 65 } 66 errMsg = ""; 67 return dt; 68 } 69 catch (Exception ex) 70 { 71 LogHelper.Log(ex); 72 errMsg = ex.Message; 73 return null; 74 } 75 finally 76 { 77 if (workbook != null) 78 { 79 workbook.Close(false, oMissiong, oMissiong); 80 System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook); 81 } 82 if (app != null) 83 { 84 app.Workbooks.Close(); 85 app.Quit(); 86 System.Runtime.InteropServices.Marshal.ReleaseComObject(app); 87 } 88 } 89 } 90 91 /// <summary> 92 /// 将excel保存到文件 93 /// </summary> 94 /// <param name="dt"></param> 95 /// <param name="excelPath"></param> 96 /// <param name="errMsg"></param> 97 /// <returns></returns> 98 public static bool SaveDataTable(DataTable dt, string excelPath, out string errMsg) 99 { 100 var result = SaveDt(dt, excelPath, out errMsg); 101 GC.Collect(); 102 GC.WaitForPendingFinalizers(); 103 GC.Collect(); 104 GC.WaitForPendingFinalizers(); 105 return result; 106 } 107 108 private static bool SaveDt(DataTable dt, string excelFilePath, out string errMsg) 109 { 110 Microsoft.Office.Interop.Excel.Application app = null; 111 Microsoft.Office.Interop.Excel._Workbook workbook = null; 112 object oMissiong = System.Reflection.Missing.Value; 113 try 114 { 115 app = new Microsoft.Office.Interop.Excel.Application 116 { 117 DisplayAlerts = false 118 }; 119 workbook = app.Workbooks.Add(true); 120 121 //将数据读入到DataTable中 122 var worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets.Item[1]; //读取第一张表 123 if (worksheet == null) 124 { 125 errMsg = "打开excel失败,请确保excel安装环境正确"; 126 return false; 127 } 128 var iRowCount = dt.Rows.Count; 129 var iColCount = dt.Columns.Count; 130 //生成列头 131 for (var i = 0; i < iColCount; i++) 132 { 133 worksheet.Cells[1, i + 1] = dt.Columns[i].ColumnName; 134 } 135 for (var iRow = 2; iRow <= iRowCount; iRow++) 136 { 137 for (var iCol = 1; iCol <= iColCount; iCol++) 138 { 139 worksheet.Cells[iRow, iCol] = dt.Rows[iRow - 2][iCol - 1].ToString(); 140 } 141 } 142 errMsg = ""; 143 return true; 144 } 145 catch (Exception ex) 146 { 147 LogHelper.Log(ex); 148 errMsg = ex.Message; 149 return false; 150 } 151 finally 152 { 153 if (workbook != null) 154 { 155 workbook.Close(true, excelFilePath, oMissiong); 156 System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook); 157 } 158 if (app != null) 159 { 160 app.Workbooks.Close(); 161 app.Quit(); 162 System.Runtime.InteropServices.Marshal.ReleaseComObject(app); 163 } 164 } 165 } 166 }
感谢阅读