OPNPOIRow.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  1. using CsvHelper;
  2. using CsvHelper.Configuration;
  3. using NPOI.SS.UserModel;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.ComponentModel;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Linq.Expressions;
  10. using System.Reflection;
  11. using System.Text;
  12. using System.Text.RegularExpressions;
  13. using XYY.Core.Standard.ExcelHelper.MSExcelHelper;
  14. namespace XYY.Core.Standard.ExcelHelper
  15. {
  16. public class OPNPOIRow
  17. {
  18. public OPNPOIRow(IRow row)
  19. {
  20. Row = row;
  21. }
  22. public IRow Row
  23. {
  24. get;
  25. }
  26. public OPNPOIRow Cell(string value)
  27. {
  28. ICell cell = Row.CreateCell(Row.Cells.Count);
  29. LastCell = cell;
  30. cell.SetCellValue(value);
  31. return this;
  32. }
  33. public ICell LastCell { get; set; }
  34. public byte[] WBToByte(IWorkbook wb)
  35. {
  36. NpoiMemoryStream ms = new NpoiMemoryStream
  37. {
  38. AllowClose = false
  39. };
  40. wb.Write(ms);
  41. byte[] data = new byte[ms.Length];
  42. ms.Seek(0, SeekOrigin.Begin);
  43. ms.Read(data, 0, data.Length);
  44. ms.AllowClose = true;
  45. return data;
  46. }
  47. }
  48. /// <summary>
  49. /// NPOI Row与对象间的转换处理
  50. /// </summary>
  51. /// <typeparam name="T">处理对象</typeparam>
  52. public class OPNPOIRow<T> : OPNPOIRow
  53. where T : class, new()
  54. {
  55. public OPNPOIRow(T model, IRow row) : base(row)
  56. {
  57. Model = model;
  58. CellExpressions = new List<LambdaExpression>();
  59. }
  60. public T Model
  61. {
  62. get;
  63. }
  64. public List<LambdaExpression> CellExpressions
  65. {
  66. get; set;
  67. }
  68. /// <summary>
  69. /// NPOIExcel列反序列化对象
  70. /// </summary>
  71. public void Deserialize()
  72. {
  73. int emptyCellCount = 0;
  74. IRow topRow = Row.Sheet.GetRow(0);
  75. for (int i = 0; i < topRow.LastCellNum; i++)
  76. {
  77. ICell topCell = topRow.GetCell(i);
  78. if (topCell != null && topCell.CellType == CellType.String)
  79. {
  80. string name = topCell.StringCellValue;
  81. ICell cell = Row.GetCell(i);
  82. if (cell == null || cell.CellType == CellType.Blank)
  83. emptyCellCount++;
  84. if (emptyCellCount == topRow.LastCellNum)
  85. {
  86. //全部空记录时直接返回
  87. break;
  88. }
  89. //过滤空行
  90. if (cell != null && cell.CellType != CellType.Blank)
  91. {
  92. if (topCell.CellComment == null)
  93. {
  94. SetPropertyVal(cell, name, Model);
  95. }
  96. else
  97. {
  98. //根据注解的序号生成List并进行实体与属性填充
  99. string[] propertyConfig = topCell.CellComment.String.String.Split('-');
  100. string pName = propertyConfig[0];
  101. int index = int.Parse(propertyConfig[1]);
  102. PropertyInfo p = typeof(T).GetProperty(pName);
  103. Type type = typeof(List<>);
  104. //目前仅解析List<T>数组
  105. if (p.PropertyType.GetGenericTypeDefinition() == type)
  106. {
  107. object list = null;
  108. object pModel = null;
  109. int count = 0;
  110. if (p.GetValue(Model, null) == null)
  111. {
  112. //实例化所有组员
  113. list = Activator.CreateInstance(p.PropertyType);
  114. p.SetValue(Model, list);
  115. }
  116. else
  117. {
  118. list = p.GetValue(Model, null);
  119. }
  120. count = (int)(list.GetType().GetProperty("Count").GetValue(list));
  121. if (count < index)
  122. {
  123. MethodInfo method = p.PropertyType.GetMethod("Add");
  124. pModel = Activator.CreateInstance(p.PropertyType.GenericTypeArguments[0]);
  125. method.Invoke(list, new object[] { pModel });
  126. }
  127. else
  128. {
  129. MethodInfo method = p.PropertyType.GetMethod("get_Item");
  130. pModel = method.Invoke(list, new object[] { index - 1 });
  131. }
  132. Type pModelType = pModel.GetType();
  133. string pModelPropertyName = name;
  134. SetPropertyVal(cell, name.Split('-')[0], pModel);
  135. }
  136. }
  137. }
  138. }
  139. }
  140. }
  141. /// <summary>
  142. /// NPOI 数据转换为C#类上的属性
  143. /// </summary>
  144. /// <param name="cell">数据</param>
  145. /// <param name="name">需赋值的列的DisplayName</param>
  146. /// <param name="model">需赋值的实体</param>
  147. private void SetPropertyVal(ICell cell, string name, object model)
  148. {
  149. //根据DisplayName查找相关的属性
  150. PropertyInfo p = model.GetType().GetProperties().Where(x =>
  151. {
  152. DisplayNameAttribute attr = x.GetCustomAttribute(typeof(DisplayNameAttribute)) as DisplayNameAttribute;
  153. if (attr != null)
  154. {
  155. return (attr.DisplayName == name);
  156. }
  157. else
  158. {
  159. return false;
  160. }
  161. }).FirstOrDefault();
  162. //类型转换
  163. if (p != null)
  164. {
  165. if (p.PropertyType == typeof(string))
  166. {
  167. if (cell.CellType == CellType.Numeric)
  168. {
  169. p.SetValue(model, cell.NumericCellValue.ToString(), null);
  170. }
  171. else
  172. {
  173. if (cell.StringCellValue.Contains("("))
  174. {
  175. p.SetValue(model, cell.StringCellValue.TrimEnd(')').Split('(')[1], null);
  176. }
  177. else
  178. {
  179. p.SetValue(model, cell.StringCellValue, null);
  180. }
  181. }
  182. }
  183. else if (p.PropertyType == typeof(int) || p.PropertyType == typeof(decimal) || p.PropertyType == typeof(float) || p.PropertyType == typeof(Enum))
  184. {
  185. if (cell.CellType == CellType.String)
  186. {
  187. if (cell.StringCellValue.Split('-').Length > 1)
  188. {
  189. p.SetValue(model, int.Parse(cell.StringCellValue.Split('-')[1]), null);
  190. }
  191. }
  192. else
  193. {
  194. if (p.PropertyType == typeof(int))
  195. {
  196. p.SetValue(model, (int)cell.NumericCellValue, null);
  197. }
  198. else if (p.PropertyType == typeof(decimal))
  199. {
  200. p.SetValue(model, (decimal)cell.NumericCellValue, null);
  201. }
  202. }
  203. }
  204. else if (p.PropertyType == typeof(DateTime))
  205. {
  206. p.SetValue(model, cell.DateCellValue, null);
  207. }
  208. else if (p.PropertyType == typeof(Nullable<DateTime>))
  209. {
  210. p.SetValue(model, cell.DateCellValue, null);
  211. }
  212. else if (p.PropertyType == typeof(bool))
  213. {
  214. p.SetValue(model, cell.BooleanCellValue, null);
  215. }
  216. else
  217. {
  218. p.SetValue(model, cell.StringCellValue, null);
  219. }
  220. }
  221. else
  222. {
  223. return;
  224. }
  225. }
  226. public void Serialize()
  227. {
  228. Serialize(Model, Row);
  229. }
  230. List<T> refData = new List<T>();
  231. public void MSSerialize(T t, IRow row)
  232. {
  233. refData.Add(t);
  234. }
  235. public void CSVSerialize(T t, IRow row)
  236. {
  237. refData.Add(t);
  238. }
  239. public byte[] ToMSExcel()
  240. {
  241. var customerMap = new MSExcelDefaultMapping<T>();
  242. foreach (LambdaExpression expression in CellExpressions)
  243. {
  244. MemberExpression memberExpression = expression.Body as MemberExpression;
  245. PropertyInfo propertyInfo = memberExpression.Member as PropertyInfo;
  246. IList<CustomAttributeTypedArgument> displayNameAttr =
  247. propertyInfo.CustomAttributes.Where(x => x.AttributeType == typeof(DisplayNameAttribute)).Select(x => x.ConstructorArguments).FirstOrDefault();
  248. var m = customerMap.Map(memberExpression.Member);
  249. if (displayNameAttr != null)
  250. {
  251. m.Name(displayNameAttr[0].Value as string);
  252. }
  253. else
  254. {
  255. m.Name(propertyInfo.Name);
  256. }
  257. }
  258. if (!System.IO.Directory.Exists(tempPath))
  259. System.IO.Directory.CreateDirectory(tempPath);
  260. var msHelper = new MSExcelHelper.MSExcelHelper();
  261. return msHelper.OutDataAsByte(refData, customerMap);
  262. }
  263. readonly string tempPath = AppContext.BaseDirectory + "\\temp";
  264. public byte[] ToCsv()
  265. {
  266. var customerMap = new DefaultClassMap<T>();
  267. foreach (LambdaExpression expression in CellExpressions)
  268. {
  269. MemberExpression memberExpression = expression.Body as MemberExpression;
  270. PropertyInfo propertyInfo = memberExpression.Member as PropertyInfo;
  271. IList<CustomAttributeTypedArgument> displayNameAttr =
  272. propertyInfo.CustomAttributes.Where(x => x.AttributeType == typeof(DisplayNameAttribute)).Select(x => x.ConstructorArguments).FirstOrDefault();
  273. var m = customerMap.Map(typeof(T), memberExpression.Member);
  274. if (displayNameAttr != null)
  275. {
  276. m.Name(displayNameAttr[0].Value as string);
  277. }
  278. else
  279. {
  280. m.Name(propertyInfo.Name);
  281. }
  282. }
  283. if (!System.IO.Directory.Exists(tempPath))
  284. System.IO.Directory.CreateDirectory(tempPath);
  285. string filePath = tempPath + "\\" + Guid.NewGuid() + ".csv";
  286. using (var writer = new StreamWriter(filePath, false, Encoding.UTF8))
  287. {
  288. using (var csv = new CsvWriter(writer, System.Globalization.CultureInfo.InvariantCulture))
  289. {
  290. csv.WriteRecords(refData);
  291. }
  292. }
  293. var data = File.ReadAllBytes(filePath);
  294. File.Delete(filePath);
  295. return data;
  296. }
  297. public void Serialize(T t, IRow row)
  298. {
  299. foreach (LambdaExpression expression in CellExpressions)
  300. {
  301. object value = expression.Compile().DynamicInvoke(t);
  302. int cellNum = row.LastCellNum == -1 ? 0 : row.LastCellNum;
  303. if (value != null)
  304. {
  305. if (value.GetType() == typeof(string))
  306. {
  307. ICell cell = row.CreateCell(cellNum);
  308. cell.SetCellValue(value as string);
  309. }
  310. else if (
  311. value.GetType() == typeof(int) ||
  312. value.GetType() == typeof(long) ||
  313. value.GetType() == typeof(uint) ||
  314. value.GetType() == typeof(ulong) ||
  315. value.GetType() == typeof(short) ||
  316. value.GetType() == typeof(sbyte) ||
  317. value.GetType() == typeof(byte) ||
  318. value.GetType() == typeof(ushort) ||
  319. value.GetType() == typeof(decimal) ||
  320. value.GetType() == typeof(float) ||
  321. value.GetType() == typeof(double)
  322. )
  323. {
  324. ICell cell = row.CreateCell(cellNum);
  325. cell.SetCellValue(Convert.ToDouble(value));
  326. }
  327. else if (value.GetType() == typeof(bool))
  328. {
  329. ICell cell = row.CreateCell(cellNum);
  330. cell.SetCellValue(Convert.ToBoolean(value));
  331. }
  332. else if (value.GetType() == typeof(DateTime))
  333. {
  334. ICell cell = row.CreateCell(cellNum);
  335. cell.SetCellValue(Convert.ToDateTime(value));
  336. }
  337. else
  338. {
  339. ICell cell = row.CreateCell(cellNum);
  340. cell.SetCellValue(value as string);
  341. }
  342. }
  343. else
  344. {
  345. ICell cell = row.CreateCell(cellNum, CellType.Blank);
  346. }
  347. }
  348. }
  349. /// <summary>
  350. /// 获取相关注解区域的最大值(已停用)
  351. /// </summary>
  352. /// <param name="topRow"></param>
  353. /// <returns></returns>
  354. private int GetDeserializeListCount(IRow topRow)
  355. {
  356. Regex numberRegex = new Regex("\\d+");
  357. int qty = 0;
  358. for (int i = 0; i < topRow.LastCellNum; i++)
  359. {
  360. ICell cell = topRow.GetCell(i);
  361. if (cell.CellComment != null)
  362. {
  363. Match match = numberRegex.Match(cell.CellComment.String.String);
  364. if (match.Success)
  365. {
  366. int index = int.Parse(match.Value);
  367. if (index > qty)
  368. {
  369. qty = index;
  370. }
  371. }
  372. }
  373. }
  374. return qty;
  375. }
  376. }
  377. /// <summary>
  378. /// NOPIRow 扩展类
  379. /// </summary>
  380. public static class OPNPOIRowExpress
  381. {
  382. /// <summary>
  383. /// 根据表达式生成列头标签(读取相关的DisplayName)
  384. /// </summary>
  385. /// <typeparam name="TModel"></typeparam>
  386. /// <typeparam name="TProperty"></typeparam>
  387. /// <param name="Row"></param>
  388. /// <param name="expression"></param>
  389. /// <param name="suffix"></param>
  390. /// <returns></returns>
  391. public static OPNPOIRow<TModel> Cell<TModel, TProperty>(this OPNPOIRow<TModel> Row, Expression<Func<TModel, TProperty>> expression, string suffix = null) where TModel : class, new()
  392. {
  393. if (expression.Body.NodeType == ExpressionType.MemberAccess)
  394. {
  395. MemberExpression memberExpression = expression.Body as MemberExpression;
  396. PropertyInfo propertyInfo = memberExpression.Member as PropertyInfo;
  397. IList<CustomAttributeTypedArgument> displayNameAttr = propertyInfo.CustomAttributes.Where(x => x.AttributeType == typeof(DisplayNameAttribute)).Select(x => x.ConstructorArguments).FirstOrDefault();
  398. Row.CellExpressions.Add(expression);
  399. if (displayNameAttr != null)
  400. {
  401. string name = displayNameAttr[0].Value as string;
  402. Row.Cell(name + suffix);
  403. }
  404. else
  405. {
  406. Row.Cell(propertyInfo.Name);
  407. }
  408. return Row;
  409. }
  410. return null;
  411. }
  412. public static OPNPOIRow<TModel> CellWithName<TModel, TProperty>(this OPNPOIRow<TModel> Row, Expression<Func<TModel, TProperty>> expression, string colName) where TModel : class, new()
  413. {
  414. if (expression.Body.NodeType == ExpressionType.MemberAccess)
  415. {
  416. MemberExpression memberExpression = expression.Body as MemberExpression;
  417. PropertyInfo propertyInfo = memberExpression.Member as PropertyInfo;
  418. Row.CellExpressions.Add(expression);
  419. if (!string.IsNullOrEmpty(colName))
  420. {
  421. Row.Cell(colName);
  422. }
  423. else
  424. {
  425. Row.Cell(propertyInfo.Name);
  426. }
  427. return Row;
  428. }
  429. return null;
  430. }
  431. }
  432. public static class WBWriteExpress
  433. {
  434. public static byte[] WriteBytes(this IWorkbook wb)
  435. {
  436. NpoiMemoryStream ms = new NpoiMemoryStream
  437. {
  438. AllowClose = false
  439. };
  440. wb.Write(ms);
  441. byte[] data = new byte[ms.Length];
  442. ms.Seek(0, SeekOrigin.Begin);
  443. ms.Read(data, 0, data.Length);
  444. ms.AllowClose = true;
  445. return data;
  446. }
  447. }
  448. /// <summary>
  449. /// NOPI流的特殊处理
  450. /// </summary>
  451. public class NpoiMemoryStream : MemoryStream
  452. {
  453. public NpoiMemoryStream()
  454. {
  455. AllowClose = true;
  456. }
  457. public bool AllowClose { get; set; }
  458. public override void Close()
  459. {
  460. if (AllowClose)
  461. {
  462. base.Close();
  463. }
  464. }
  465. public NpoiMemoryStream(Stream stream) : this()
  466. {
  467. byte[] data = new byte[stream.Length];
  468. stream.Read(data, 0, data.Length);
  469. Write(data, 0, data.Length);
  470. stream.Close();
  471. Seek(0, SeekOrigin.Begin);
  472. }
  473. }
  474. }