Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

365 řádky
12 KiB

  1. using NPOI.SS.UserModel;
  2. using NPOI.HSSF.UserModel;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. using System.Reflection;
  9. using System.Collections;
  10. using NPOI.XSSF.UserModel;
  11. using NPOI.HSSF.Util;
  12. namespace HKHelper
  13. {
  14. /// <summary>
  15. /// excel转object
  16. /// </summary>
  17. public class ExcelAttribute : Attribute
  18. {
  19. public ExcelAttribute(string name)
  20. {
  21. Title = name;
  22. }
  23. public int Order { get; set; }
  24. public string Title { get; set; }
  25. }
  26. public class ExcelImporter
  27. {
  28. public IEnumerable<TModel> ExcelToObject<TModel>(string path, int? type = null) where TModel : class, new()
  29. {
  30. var result = GetDataRows(path);
  31. var dict = ExcelUtil.GetExportAttrDict<TModel>();
  32. var dictColumns = new Dictionary<int, KeyValuePair<PropertyInfo, ExcelAttribute>>();
  33. IEnumerator rows = result;
  34. var titleRow = (IRow)rows.Current;
  35. if (titleRow != null)
  36. foreach (var cell in titleRow.Cells)
  37. {
  38. var prop = new KeyValuePair<PropertyInfo, ExcelAttribute>();
  39. foreach (var item in dict)
  40. {
  41. if (cell.StringCellValue == item.Value.Title)
  42. {
  43. prop = item;
  44. }
  45. }
  46. if (prop.Key != null && !dictColumns.ContainsKey(cell.ColumnIndex))
  47. {
  48. dictColumns.Add(cell.ColumnIndex, prop);
  49. }
  50. }
  51. while (rows.MoveNext())
  52. {
  53. var row = (IRow)rows.Current;
  54. if (row != null)
  55. {
  56. var firstCell = row.GetCell(0);
  57. if (firstCell == null || firstCell.CellType == CellType.Blank ||
  58. string.IsNullOrEmpty(firstCell.ToString()))
  59. continue;
  60. }
  61. var model = new TModel();
  62. foreach (var pair in dictColumns)
  63. {
  64. var propType = pair.Value.Key.PropertyType;
  65. if (propType == typeof(DateTime?) ||
  66. propType == typeof(DateTime))
  67. {
  68. pair.Value.Key.SetValue(model, GetCellDateTime(row, pair.Key), null);
  69. }
  70. else
  71. {
  72. try
  73. {
  74. var val = Convert.ChangeType(GetCellValue(row, pair.Key), propType);
  75. pair.Value.Key.SetValue(model, val, null);
  76. }
  77. catch (Exception ex)
  78. {
  79. break;
  80. }
  81. }
  82. }
  83. yield return model;
  84. }
  85. }
  86. string GetCellValue(IRow row, int index)
  87. {
  88. var result = string.Empty;
  89. try
  90. {
  91. switch (row.GetCell(index).CellType)
  92. {
  93. case CellType.Numeric:
  94. result = row.GetCell(index).NumericCellValue.ToString();
  95. break;
  96. case CellType.String:
  97. result = row.GetCell(index).StringCellValue;
  98. break;
  99. case CellType.Blank:
  100. result = string.Empty;
  101. break;
  102. #region
  103. //case CellType.Formula:
  104. // result = row.GetCell(index).CellFormula;
  105. // break;
  106. //case CellType.Boolean:
  107. // result = row.GetCell(index).NumericCellValue.ToString();
  108. // break;
  109. //case CellType.Error:
  110. // result = row.GetCell(index).NumericCellValue.ToString();
  111. // break;
  112. //case CellType.Unknown:
  113. // result = row.GetCell(index).NumericCellValue.ToString();
  114. // break;
  115. #endregion
  116. default:
  117. result = row.GetCell(index).ToString();
  118. break;
  119. }
  120. }
  121. catch (Exception e)
  122. {
  123. Console.WriteLine(e);
  124. }
  125. return (result ?? "").Trim();
  126. }
  127. IEnumerator GetDataRows(string path)
  128. {
  129. if (string.IsNullOrEmpty(path))
  130. return null;
  131. HSSFWorkbook hssfworkbook;
  132. try
  133. {
  134. using (FileStream file = new FileStream(path, FileMode.Open, FileAccess.Read))
  135. {
  136. hssfworkbook = new HSSFWorkbook(file);
  137. }
  138. }
  139. catch (Exception)
  140. {
  141. return null;
  142. }
  143. ISheet sheet = hssfworkbook.GetSheetAt(0);
  144. IEnumerator rows = sheet.GetRowEnumerator();
  145. rows.MoveNext();
  146. return rows;
  147. }
  148. DateTime? GetCellDateTime(IRow row, int index)
  149. {
  150. DateTime? result = null;
  151. try
  152. {
  153. switch (row.GetCell(index).CellType)
  154. {
  155. case CellType.Numeric:
  156. try
  157. {
  158. result = row.GetCell(index).DateCellValue;
  159. }
  160. catch (Exception e)
  161. {
  162. Console.WriteLine(e);
  163. }
  164. break;
  165. case CellType.String:
  166. var str = row.GetCell(index).StringCellValue;
  167. if (str.EndsWith("年"))
  168. {
  169. DateTime dt;
  170. if (DateTime.TryParse((str + "-01-01").Replace("年", ""), out dt))
  171. {
  172. result = dt;
  173. }
  174. }
  175. else if (str.EndsWith("月"))
  176. {
  177. DateTime dt;
  178. if (DateTime.TryParse((str + "-01").Replace("年", "").Replace("月", ""), out dt))
  179. {
  180. result = dt;
  181. }
  182. }
  183. else if (!str.Contains("年") && !str.Contains("月") && !str.Contains("日"))
  184. {
  185. try
  186. {
  187. result = Convert.ToDateTime(str);
  188. }
  189. catch (Exception)
  190. {
  191. try
  192. {
  193. result = Convert.ToDateTime((str + "-01-01").Replace("年", "").Replace("月", ""));
  194. }
  195. catch (Exception)
  196. {
  197. result = null;
  198. }
  199. }
  200. }
  201. else
  202. {
  203. DateTime dt;
  204. if (DateTime.TryParse(str.Replace("年", "").Replace("月", ""), out dt))
  205. {
  206. result = dt;
  207. }
  208. }
  209. break;
  210. case CellType.Blank:
  211. break;
  212. #region
  213. #endregion
  214. }
  215. }
  216. catch (Exception e)
  217. {
  218. Console.WriteLine(e);
  219. }
  220. return result;
  221. }
  222. }
  223. public class ExcelExporter
  224. {
  225. public byte[] ObjectToExcelBytes<TModel>(IEnumerable<TModel> data)
  226. {
  227. var workbook = new HSSFWorkbook();
  228. var sheet = workbook.CreateSheet();
  229. var attrDict = ExcelUtil.GetExportAttrDict<TModel>();
  230. List<KeyValuePair<PropertyInfo, ExcelAttribute>> attrArray = new List<KeyValuePair<PropertyInfo, ExcelAttribute>>();
  231. int aNum = 0;
  232. foreach (var item in attrDict)
  233. {
  234. attrArray.Add(item);
  235. aNum++;
  236. }
  237. for (int i = 0; i < attrArray.Count; i++)
  238. {
  239. sheet.SetColumnWidth(i, 50 * 256);
  240. }
  241. var headerRow = sheet.CreateRow(0);
  242. for (int i = 0; i < attrArray.Count; i++)
  243. {
  244. if (attrArray[i].Value != null)
  245. {
  246. headerRow.CreateCell(i).SetCellValue(attrArray[i].Value.Title);
  247. }
  248. }
  249. int rowNumber = 1;
  250. foreach (var item in data)
  251. {
  252. var row = sheet.CreateRow(rowNumber++);
  253. for (int i = 0; i < attrArray.Count; i++)
  254. {
  255. if (attrArray[i].Value != null)
  256. {
  257. row.CreateCell(i).SetCellValue((attrArray[i].Key.GetValue(item, null) ?? "").ToString());
  258. }
  259. }
  260. }
  261. using (var output = new MemoryStream())
  262. {
  263. workbook.Write(output);
  264. var bytes = output.ToArray();
  265. return bytes;
  266. }
  267. }
  268. }
  269. public class ExcelHelper
  270. {
  271. /// <summary>
  272. /// import file excel file to a IEnumerable of TModel
  273. /// </summary>
  274. /// <typeparam name="TModel"></typeparam>
  275. /// <param name="path">excel full path</param>
  276. /// <returns></returns>
  277. public static IEnumerable<TModel> ExcelToObject<TModel>(string path) where TModel : class, new()
  278. {
  279. var importer = new ExcelImporter();
  280. return importer.ExcelToObject<TModel>(path);
  281. }
  282. /// <summary>
  283. /// Export object to excel file
  284. /// </summary>
  285. /// <typeparam name="TModel"></typeparam>
  286. /// <param name="data">a IEnumerable of TModel</param>
  287. /// <param name="path">excel full path</param>
  288. public static void ObjectToExcel<TModel>(IEnumerable<TModel> data, string path) where TModel : class, new()
  289. {
  290. var importer = new ExcelExporter();
  291. var bytes = importer.ObjectToExcelBytes(data);
  292. File.WriteAllBytes(path, bytes);
  293. }
  294. }
  295. internal class ExcelUtil
  296. {
  297. public static Dictionary<PropertyInfo, ExcelAttribute> GetExportAttrDict<T>()
  298. {
  299. var dict = new Dictionary<PropertyInfo, ExcelAttribute>();
  300. foreach (var propertyInfo in typeof(T).GetProperties())
  301. {
  302. var attr = new object();
  303. var ppi = propertyInfo.GetCustomAttributes(true);
  304. for (int i = 0; i < ppi.Length; i++)
  305. {
  306. if (ppi[i] is ExcelAttribute)
  307. {
  308. attr = ppi[i];
  309. break;
  310. }
  311. }
  312. if (attr != null)
  313. {
  314. dict.Add(propertyInfo, attr as ExcelAttribute);
  315. }
  316. }
  317. return dict;
  318. }
  319. }
  320. public class UserDtoModel
  321. {
  322. [Excel("姓名", Order = 1)]
  323. public string Name { get; set; }
  324. [Excel("组织机构", Order = 2)]
  325. public string OrgId { get; set; }
  326. }
  327. }