ContractUtil.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. using System.IO;
  2. using DocumentFormat.OpenXml;
  3. using DocumentFormat.OpenXml.Packaging;
  4. using DocumentFormat.OpenXml.Spreadsheet;
  5. using UniformMaterialManagementSystem.Entities;
  6. namespace UniformMaterialManagementSystem.Utils
  7. {
  8. public static class ContractUtil
  9. {
  10. public static void ExportToExcel(string path, List<ContractDetail> contracts, Dictionary<string, string> dictionary)
  11. {
  12. var templateFilePath = "Template\\附件1被装材料采购合同明细数据模板.xlsx";
  13. File.Copy(templateFilePath, path);
  14. using var spreadsheetDocument = SpreadsheetDocument.Open(path, isEditable: true);
  15. var workbookPart = spreadsheetDocument.WorkbookPart;
  16. var sheets = spreadsheetDocument.WorkbookPart?.Workbook.GetFirstChild<Sheets>()?.Elements<Sheet>();
  17. var relationshipId = sheets?.First().Id?.Value;
  18. if (relationshipId == null) return;
  19. var worksheetPart = (WorksheetPart?)workbookPart?.GetPartById(relationshipId);
  20. if (worksheetPart == null) return;
  21. var worksheet = worksheetPart.Worksheet;
  22. var sheetData = worksheet.GetFirstChild<SheetData>();
  23. var stylesPart = workbookPart?.WorkbookStylesPart;
  24. if (stylesPart != null)
  25. {
  26. UpdateStyleSheet(stylesPart.Stylesheet);
  27. }
  28. // 修改成品企业名称
  29. var cellReference = "C3";
  30. var cell = sheetData?.Descendants<Cell>().FirstOrDefault(c => c.CellReference?.Value == cellReference);
  31. if (cell != null) // 解决直接更新单元格,Excel报错问题,先删后插
  32. {
  33. cell.Remove();
  34. var rowIndex = uint.Parse(new string(cellReference.Where(char.IsDigit).ToArray()));
  35. var row = sheetData?.Elements<Row>().FirstOrDefault(r => r.RowIndex?.Value == rowIndex);
  36. if (row == null)
  37. {
  38. row = new Row() { RowIndex = rowIndex };
  39. sheetData?.Append(row);
  40. }
  41. var refCell = row.Elements<Cell>().FirstOrDefault(c => string.Compare(c.CellReference?.Value, cellReference, StringComparison.OrdinalIgnoreCase) > 0);
  42. var companyName = dictionary.ContainsKey("ProductCompanyName") ? dictionary["ProductCompanyName"] : "";
  43. var newCell = new Cell
  44. {
  45. CellReference = cellReference,
  46. DataType = new EnumValue<CellValues>(CellValues.String),
  47. CellValue = new CellValue(companyName) //Todo:输入成品企业名称
  48. };
  49. row.InsertBefore(newCell, refCell);
  50. }
  51. // 修改填报人及电话
  52. var editUserCellReference = "D3";
  53. var editUserCell = sheetData?.Descendants<Cell>().FirstOrDefault(c => c.CellReference?.Value == editUserCellReference);
  54. if (editUserCell != null) // 解决直接更新单元格,Excel报错问题,先删后插
  55. {
  56. editUserCell.Remove();
  57. var rowIndex = uint.Parse(new string(editUserCellReference.Where(char.IsDigit).ToArray()));
  58. var row = sheetData?.Elements<Row>().FirstOrDefault(r => r.RowIndex?.Value == rowIndex);
  59. if (row == null)
  60. {
  61. row = new Row() { RowIndex = rowIndex };
  62. sheetData?.Append(row);
  63. }
  64. var refCell = row.Elements<Cell>().FirstOrDefault(c => string.Compare(c.CellReference?.Value, editUserCellReference, StringComparison.OrdinalIgnoreCase) > 0);
  65. var editUserAndTel = dictionary.ContainsKey("EditUserAndTel") ? dictionary["EditUserAndTel"] : "";
  66. var newCell = new Cell
  67. {
  68. CellReference = editUserCellReference,
  69. DataType = new EnumValue<CellValues>(CellValues.String),
  70. CellValue = new CellValue("填报人及电话:" + editUserAndTel) //Todo:输入填报人及联系电话
  71. };
  72. row.InsertBefore(newCell, refCell);
  73. }
  74. // 修改填报日期
  75. var editDateCellReference = "G3";
  76. var editDateCell = sheetData?.Descendants<Cell>().FirstOrDefault(c => c.CellReference?.Value == editDateCellReference);
  77. if (editDateCell != null) // 解决直接更新单元格,Excel报错问题,先删后插
  78. {
  79. editDateCell.Remove();
  80. var rowIndex = uint.Parse(new string(editDateCellReference.Where(char.IsDigit).ToArray()));
  81. var row = sheetData?.Elements<Row>().FirstOrDefault(r => r.RowIndex?.Value == rowIndex);
  82. if (row == null)
  83. {
  84. row = new Row() { RowIndex = rowIndex };
  85. sheetData?.Append(row);
  86. }
  87. var refCell = row.Elements<Cell>().FirstOrDefault(c => string.Compare(c.CellReference?.Value, editDateCellReference, StringComparison.OrdinalIgnoreCase) > 0);
  88. var editDate = dictionary.ContainsKey("EditDate") ? dictionary["EditDate"] : "";
  89. var newCell = new Cell
  90. {
  91. CellReference = editDateCellReference,
  92. DataType = new EnumValue<CellValues>(CellValues.String),
  93. CellValue = new CellValue("填报日期:" + editDate) //Todo:输入填报日期
  94. };
  95. row.InsertBefore(newCell, refCell);
  96. }
  97. // 添加明细
  98. var styleCount = stylesPart?.Stylesheet.CellFormats?.Count;
  99. for (var i = 0; i < contracts.Count; i++)
  100. {
  101. var row = new Row() { RowIndex = (UInt32Value)((uint)i + 5) };
  102. var numberCell = new Cell
  103. {
  104. DataType = new EnumValue<CellValues>(CellValues.Number),
  105. CellValue = new CellValue(i + 1),
  106. StyleIndex = styleCount == null ? 0 : styleCount - 4
  107. };
  108. var contractNoCell = new Cell
  109. {
  110. DataType = new EnumValue<CellValues>(CellValues.String),
  111. CellValue = new CellValue(contracts[i].Contract.ContractNo),
  112. StyleIndex = styleCount == null ? 0 : styleCount - 1
  113. };
  114. var companyNameCell = new Cell
  115. {
  116. DataType = new EnumValue<CellValues>(CellValues.String),
  117. CellValue = new CellValue(contracts[i].Contract.Company.Name),
  118. StyleIndex = styleCount == null ? 0 : styleCount - 1
  119. };
  120. var signTimeCell = new Cell()
  121. {
  122. DataType = new EnumValue<CellValues>(CellValues.String),
  123. CellValue = new CellValue(contracts[i].Contract.SigningDate.ToString("yyyy-M-dd")),
  124. StyleIndex = styleCount == null ? 0 : styleCount - 3
  125. };
  126. var materialNameCell = new Cell()
  127. {
  128. DataType = new EnumValue<CellValues>(CellValues.String),
  129. CellValue = new CellValue(contracts[i].Material.Name),
  130. StyleIndex = styleCount == null ? 0 : styleCount - 1
  131. };
  132. var measureUnitCell = new Cell()
  133. {
  134. DataType = new EnumValue<CellValues>(CellValues.String),
  135. CellValue = new CellValue(contracts[i].Material.MeasureUnit),
  136. StyleIndex = styleCount == null ? 0 : styleCount - 1
  137. };
  138. var contractQtyCell = new Cell()
  139. {
  140. DataType = new EnumValue<CellValues>(CellValues.Number),
  141. CellValue = new CellValue(contracts[i].ContractQty),
  142. StyleIndex = styleCount == null ? 0 : styleCount - 2
  143. };
  144. var deliveryTimeCell = new Cell()
  145. {
  146. DataType = new EnumValue<CellValues>(CellValues.String),
  147. CellValue = new CellValue(contracts[i].DeliveryTime.ToString("yyyy-M-dd")),
  148. StyleIndex = styleCount == null ? 0 : styleCount - 3
  149. };
  150. row.Append(numberCell);
  151. row.Append(contractNoCell);
  152. row.Append(companyNameCell);
  153. row.Append(signTimeCell);
  154. row.Append(materialNameCell);
  155. row.Append(measureUnitCell);
  156. row.Append(contractQtyCell);
  157. row.Append(deliveryTimeCell);
  158. sheetData?.Append(row);
  159. }
  160. worksheet.Save();
  161. //var newDocument = spreadsheetDocument.Clone(path);
  162. //newDocument.Dispose();
  163. }
  164. private static void UpdateStyleSheet(Stylesheet stylesheet)
  165. {
  166. #region Number format
  167. uint datetimeFormat = 164;
  168. uint digits4Format = 165;
  169. var numberingFormats = stylesheet.NumberingFormats ?? new NumberingFormats();
  170. numberingFormats.Append(new NumberingFormat // Datetime format
  171. {
  172. NumberFormatId = UInt32Value.FromUInt32(datetimeFormat),
  173. FormatCode = StringValue.FromString("yyyy-m-dd")
  174. });
  175. numberingFormats.Append(new NumberingFormat // four digits format
  176. {
  177. NumberFormatId = UInt32Value.FromUInt32(digits4Format),
  178. FormatCode = StringValue.FromString("#0.00")
  179. });
  180. numberingFormats.Count = UInt32Value.FromUInt32((uint)numberingFormats.ChildElements.Count);
  181. stylesheet.NumberingFormats ??= numberingFormats;
  182. #endregion
  183. #region Borders
  184. var borders = stylesheet.Borders ?? new Borders();
  185. borders.Append(new Border //Boarder Index 1: All
  186. {
  187. LeftBorder = new LeftBorder { Style = BorderStyleValues.Thin },
  188. RightBorder = new RightBorder { Style = BorderStyleValues.Thin },
  189. TopBorder = new TopBorder { Style = BorderStyleValues.Thin },
  190. BottomBorder = new BottomBorder { Style = BorderStyleValues.Thin },
  191. DiagonalBorder = new DiagonalBorder()
  192. });
  193. borders.Count = UInt32Value.FromUInt32((uint)borders.ChildElements.Count);
  194. stylesheet.Borders ??= borders;
  195. #endregion
  196. #region Cell format
  197. var cellFormats = stylesheet.CellFormats ?? new CellFormats();
  198. var borderCount = stylesheet.Borders?.Count;
  199. cellFormats.Append(new CellFormat
  200. {
  201. NumberFormatId = 1,
  202. BorderId = borderCount == null ? 0 : borderCount - 1,
  203. ApplyNumberFormat = BooleanValue.FromBoolean(false)
  204. });
  205. cellFormats.Append(new CellFormat
  206. {
  207. NumberFormatId = datetimeFormat,
  208. BorderId = borderCount == null ? 0 : borderCount - 1,
  209. ApplyNumberFormat = BooleanValue.FromBoolean(true)
  210. });
  211. cellFormats.Append(new CellFormat
  212. {
  213. NumberFormatId = digits4Format,
  214. BorderId = borderCount == null ? 0 : borderCount - 1,
  215. ApplyNumberFormat = BooleanValue.FromBoolean(true)
  216. });
  217. cellFormats.Append(new CellFormat
  218. {
  219. NumberFormatId = 0,
  220. BorderId = borderCount == null ? 0 : borderCount - 1,
  221. ApplyNumberFormat = BooleanValue.FromBoolean(false)
  222. });
  223. cellFormats.Count = UInt32Value.FromUInt32((uint)cellFormats.ChildElements.Count);
  224. stylesheet.CellFormats ??= cellFormats;
  225. #endregion
  226. stylesheet.Save();
  227. }
  228. }
  229. }