You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

824 lines
35 KiB

2 years ago
  1. using Aspose.Cells;
  2. using EasyBL.WebApi.Message;
  3. using EasyNet.Common;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Data;
  7. using System.Drawing;
  8. using System.Linq;
  9. using System.Reflection;
  10. namespace EasyBL
  11. {
  12. public class ExcelService : ServiceBase
  13. {
  14. public Workbook workbook;
  15. public Worksheet sheet;
  16. public ExcelService(string file = null)
  17. {
  18. workbook = !string.IsNullOrEmpty(file) ? new Workbook(file) : new Workbook();
  19. sheet = workbook.Worksheets[0];
  20. }
  21. /// <summary>
  22. /// 產出excel
  23. /// </summary>
  24. /// <param name="i_dicData"></param>
  25. /// <param name="o_sFilePath"></param>
  26. /// <param name="dicItems"></param>
  27. /// <param name="sFileName"></param>
  28. /// <param name="sSheetName"></param>
  29. /// <returns></returns>
  30. public bool CreateExcel(List<Dictionary<string, object>> i_dicData, out string o_sFilePath, Dictionary<string, object> dicItems = null, string sFileName = "", string sSheetName = "sheet1")
  31. {
  32. try
  33. {
  34. var saItemsWidth = new Dictionary<string, object>();
  35. string sFilePath = null;
  36. string sFileFullName = null;
  37. var bStatus = false;
  38. do
  39. {
  40. workbook.Worksheets[0].Name = sSheetName;
  41. var style_L = GetStyle(0, false, TextAlignmentType.Left, Color.White, false);
  42. var style_C = GetStyle(0, false, TextAlignmentType.Center, Color.White, true);
  43. var style_Header = GetStyle(12, true, TextAlignmentType.Center, Color.FromArgb(153, 204, 0), false);
  44. var cells = sheet.Cells;//单元格
  45. var iCol = dicItems == null ? i_dicData[0].Keys.Count : dicItems.Keys.Count; ;//表格列数
  46. var iRow = i_dicData.Count;//表格行数
  47. var iCurentRow = 3;//當前行
  48. //生成标题行
  49. cells.Merge(0, 0, 1, iCol);//合并单元格
  50. cells.Merge(1, 0, 1, iCol);//合并单元格
  51. cells[0, 0].PutValue(sSheetName);//填写标题
  52. cells[1, 0].PutValue("匯出時間:" + DateTime.Now.ToString("yyyy/MM/dd"));//匯出時間
  53. SetCellsStyle(new int[] { 0, 0, 1, iCol }, 14, true, TextAlignmentType.Center, Color.White);//标题row樣式
  54. SetCellsStyle(new int[] { 1, 0, 1, iCol }, 12, false, TextAlignmentType.Right, Color.White);//時間row樣式
  55. cells.SetRowHeight(0, 25);
  56. cells.SetRowHeight(1, 20);
  57. //填充表头
  58. if (dicItems != null)
  59. {
  60. var index = 0;
  61. foreach (string sKey in dicItems.Keys)
  62. {
  63. var sValue = dicItems[sKey];
  64. if (sValue == null)
  65. {
  66. sValue = "";
  67. }
  68. cells[2, index].PutValue(sValue);//表頭
  69. cells[2, index].SetStyle(style_Header);//時間Header row樣式
  70. //setCellsWisth(index, sValue.ToString(), true, saItemsWidth);
  71. index++;
  72. }
  73. }
  74. //填充内容
  75. foreach (Dictionary<string, object> oData in i_dicData)
  76. {
  77. if (dicItems != null)
  78. {
  79. var cellIndex = 0;
  80. foreach (string sKey in dicItems.Keys)
  81. {
  82. if (oData.Keys.Contains(sKey))
  83. {
  84. var sValue = oData[sKey];
  85. if (sValue == null)
  86. {
  87. sValue = "";
  88. }
  89. cells[iCurentRow, cellIndex].PutValue(sValue);//表頭
  90. if (cellIndex == 0)
  91. {
  92. cells[iCurentRow, cellIndex].SetStyle(style_C);//項次居中
  93. }
  94. else
  95. {
  96. cells[iCurentRow, cellIndex].SetStyle(style_L);//內容居左
  97. }
  98. cellIndex++;
  99. }
  100. }
  101. }
  102. else
  103. {
  104. var cellIndex = 0;
  105. foreach (string sKey in oData.Keys)
  106. {
  107. var sValue = oData[sKey];
  108. if (sValue == null)
  109. {
  110. sValue = "";
  111. }
  112. cells[iCurentRow, cellIndex].PutValue(sValue);//表頭
  113. if (cellIndex == 0)
  114. {
  115. cells[iCurentRow, cellIndex].SetStyle(style_C);//項次居中
  116. }
  117. else
  118. {
  119. cells[iCurentRow, cellIndex].SetStyle(style_L);//內容居左
  120. }
  121. //setCellsWisth(cellIndex, sValue.ToString(), true, saItemsWidth);
  122. cellIndex++;
  123. }
  124. }
  125. iCurentRow++;
  126. }
  127. //SetCellsStyle(new int[] { 3, 1, iCurentRow - 3, iCol - 1 }, 12, false, TextAlignmentType.Left, Color.White);
  128. //foreach (string key in saItemsWidth.Keys)
  129. //{
  130. // cells.SetColumnWidth(int.Parse(key), double.Parse(saItemsWidth[key].ToString()));
  131. //}
  132. //sheet.AutoFitRows();
  133. cells.SetRowHeight(2, 30);
  134. sheet.AutoFitColumns();
  135. sFilePath = Common.ConfigGetValue("", "OutFilesPath");
  136. sFileName = (sFileName ?? "") + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
  137. var sSeverPath = AppDomain.CurrentDomain.BaseDirectory + sFilePath;
  138. sFileFullName = sSeverPath + "/" + sFileName;
  139. Common.FnCreateDir(sSeverPath);
  140. //保存
  141. workbook.Save(sFileFullName);
  142. bStatus = true;
  143. }
  144. while (false);
  145. o_sFilePath = sFileFullName.Replace("\\", "/");
  146. return bStatus;
  147. }
  148. catch (Exception ex)
  149. {
  150. Logger.Error("E" + ex.Message, ex);
  151. o_sFilePath = "";
  152. return false;
  153. }
  154. }
  155. /// <summary>
  156. /// 產出excel
  157. /// </summary>
  158. /// <param name="dt"></param>
  159. /// <param name="o_sFilePath"></param>
  160. /// <param name="oHeader"></param>
  161. /// <param name="dicAlain"></param>
  162. /// <param name="Merges"></param>
  163. /// <param name="sFileName"></param>
  164. /// <param name="sSheetName"></param>
  165. /// <returns></returns>
  166. public bool CreateExcelByTb(DataTable dt, out string o_sFilePath, object oHeader = null, Dictionary<string, string> dicAlain = null, List<Dictionary<string, int>> Merges = null, string sFileName = "", string sSheetName = "sheet1")
  167. {
  168. try
  169. {
  170. var saItemsWidth = new Dictionary<string, object>();
  171. Dictionary<string, string> Headers = null;
  172. string sFilePath = null;
  173. string sFileFullName = null;
  174. var bStatus = false;
  175. if (dicAlain == null)
  176. {
  177. dicAlain = new Dictionary<string, string>();
  178. }
  179. workbook.Worksheets[0].Name = sSheetName;
  180. var cells = sheet.Cells;//单元格
  181. //为单元格添加样式
  182. var style = workbook.CreateStyle();
  183. //设置居中
  184. style.HorizontalAlignment = TextAlignmentType.Left;
  185. var style_C = GetStyle(0, false, TextAlignmentType.Center, Color.White, true);
  186. var style_L = GetStyle(0, false, TextAlignmentType.Left, Color.White, false);
  187. var style_R = GetStyle(0, false, TextAlignmentType.Right, Color.White, false);
  188. //靠右通常為數字,改成顯示數字,參考:https://apireference.aspose.com/net/cells/aspose.cells/style/properties/number
  189. style_R.Number = 4; // #,##0.00
  190. var style_Del = GetStyle(0, false, TextAlignmentType.Left, Color.LightGray, true);
  191. var style_Header = GetStyle(12, true, TextAlignmentType.Center, Color.FromArgb(153, 204, 0), false);
  192. //靠右的設定
  193. var FormatredNumber = dicAlain.Where(c => c.Value == "right" ).Select( c => c.Key).ToList();
  194. //行索引
  195. var rowIndex = 3;
  196. //列总数
  197. var colCount = dt.Columns.Count;
  198. if (oHeader != null)
  199. {
  200. if (oHeader.GetType() == typeof(Dictionary<string, string>))
  201. {
  202. Headers = oHeader as Dictionary<string, string>;
  203. SetHeader(cells, Headers, style_Header, 2);
  204. }
  205. else
  206. {
  207. SetGroupHeader(cells, oHeader, out Headers);
  208. SetHeader(cells, Headers, style_Header, 3);
  209. rowIndex++;
  210. cells.SetRowHeight(3, 30);//设置行高
  211. }
  212. colCount = Headers.Keys.Count;
  213. cells.SetRowHeight(2, 30);//设置行高
  214. }
  215. else
  216. {
  217. for (int i = 0; i < colCount; i++)
  218. {
  219. cells[2, i].PutValue(dt.Columns[i].ColumnName);
  220. cells[2, i].SetStyle(style_Header);
  221. }
  222. }
  223. //生成标题行
  224. cells.Merge(0, 0, 1, colCount);//合并单元格
  225. cells.Merge(1, 0, 1, colCount);//合并单元格
  226. cells[0, 0].PutValue(sFileName);//填写标题
  227. cells[1, 0].PutValue("匯出時間:" + DateTime.Now.ToString("yyyy/MM/dd"));//匯出時間
  228. SetCellsStyle(new int[] { 0, 0, 1, colCount }, 14, true, TextAlignmentType.Center, Color.White);//标题row樣式
  229. SetCellsStyle(new int[] { 1, 0, 1, colCount }, 12, false, TextAlignmentType.Right, Color.White);//時間row樣式
  230. cells.SetRowHeight(0, 25);
  231. cells.SetRowHeight(1, 20);
  232. foreach (DataRow row in dt.Rows)
  233. {
  234. var bDeleteRow = false;
  235. if (dt.Columns.Contains(BLWording.ISVOID) && row[BLWording.ISVOID].ToString() == "Y") { bDeleteRow = true; }
  236. //填充資料
  237. if (Headers != null)
  238. {
  239. var cellIndex = 0;
  240. foreach (string sKey in Headers.Keys)
  241. {
  242. if (row[sKey] != null)
  243. {
  244. var sValue = row[sKey];
  245. if (sValue == null)
  246. {
  247. sValue = "";
  248. }
  249. //設定值
  250. if (FormatredNumber.Contains(sKey) )
  251. {
  252. var ConvertData = sValue.ToString();
  253. cells[rowIndex, cellIndex].PutValue(ConvertData, true);
  254. }
  255. else
  256. {
  257. cells[rowIndex, cellIndex].PutValue(sValue);
  258. }
  259. //設定style:
  260. if (dicAlain.Keys.Contains(sKey))
  261. {
  262. var sVal = dicAlain[sKey].ToString();
  263. if (sVal == "center")
  264. {
  265. cells[rowIndex, cellIndex].SetStyle(style_C);//項次居中
  266. }
  267. else if (sVal == "right")
  268. {
  269. cells[rowIndex, cellIndex].SetStyle(style_R);//項次居右
  270. }
  271. else
  272. {
  273. cells[rowIndex, cellIndex].SetStyle(style_L);//項次居左
  274. }
  275. }
  276. else
  277. {
  278. cells[rowIndex, cellIndex].SetStyle(style_L);//項次居左
  279. }
  280. if (bDeleteRow)
  281. {
  282. cells[rowIndex, cellIndex].SetStyle(style_Del);//刪除的資料
  283. }
  284. cellIndex++;
  285. }
  286. }
  287. }
  288. else
  289. {
  290. for (int i = 0; i < colCount; i++)
  291. {
  292. sheet.Cells[rowIndex, i].PutValue(row[i]);
  293. if (i == 0)
  294. {
  295. cells[rowIndex, i].SetStyle(style_C);//項次居中
  296. }
  297. else
  298. {
  299. cells[rowIndex, i].SetStyle(style_L);//內容居左
  300. }
  301. if (bDeleteRow)
  302. {
  303. cells[rowIndex, i].SetStyle(style_Del);//刪除的資料
  304. }
  305. }
  306. }
  307. rowIndex++;
  308. }
  309. if (Merges != null)//合并单元格
  310. {
  311. foreach (Dictionary<string, int> Merge in Merges)
  312. {
  313. cells.Merge(Merge["FirstRow"], Merge["FirstCol"], Merge["RowCount"], Merge["ColCount"]);
  314. }
  315. }
  316. sheet.AutoFitColumns();
  317. sFilePath = Common.ConfigGetValue("", "OutFilesPath");
  318. sFileName = (sFileName ?? "") + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
  319. var sSeverPath = AppDomain.CurrentDomain.BaseDirectory + sFilePath;
  320. sFileFullName = sSeverPath + "/" + sFileName;
  321. Common.FnCreateDir(sSeverPath);
  322. workbook.Save(sFileFullName);
  323. bStatus = true;
  324. o_sFilePath = sFileFullName.Replace("\\", "/");
  325. return bStatus;
  326. }
  327. catch (Exception ex)
  328. {
  329. Logger.Error("导出文件时出错" + ex.Message, ex);
  330. //LogAndSendEmail(sMsg + "Param:" + JsonToString(i_crm), ex, i_crm.ORIGID, i_crm.USERID, "ExcelService", "Excel匯出", "CopyLanguage(複製語系檔案)", "", "", "");
  331. o_sFilePath = "";
  332. return false;
  333. }
  334. }
  335. /// <summary>
  336. /// 產出excel
  337. /// </summary>
  338. /// <typeparam name="T"></typeparam>
  339. /// <param name="list"></param>
  340. /// <param name="o_sFilePath"></param>
  341. /// <param name="dicItems"></param>
  342. /// <param name="dicAlain"></param>
  343. /// <param name="sFileName"></param>
  344. /// <param name="sSheetName"></param>
  345. /// <returns></returns>
  346. public bool CreateExcelByList<T>(IList<T> list, out string o_sFilePath, Dictionary<string, string> dicItems = null, Dictionary<string, string> dicAlain = null, string sFileName = "", string sSheetName = "sheet1") where T : new()
  347. {
  348. try
  349. {
  350. var properties = ReflectionHelper.GetProperties(new T().GetType());
  351. var saItemsWidth = new Dictionary<string, object>();
  352. string sFilePath = null;
  353. string sFileFullName = null;
  354. var bStatus = false;
  355. if (dicAlain == null)
  356. {
  357. dicAlain = new Dictionary<string, string>();
  358. }
  359. workbook.Worksheets[0].Name = sSheetName;
  360. var cells = sheet.Cells;//单元格
  361. //为单元格添加样式
  362. var style = workbook.CreateStyle();
  363. var style_L = GetStyle(0, false, TextAlignmentType.Left, Color.White, false);
  364. var style_R = GetStyle(0, false, TextAlignmentType.Right, Color.White, true);
  365. var style_C = GetStyle(0, false, TextAlignmentType.Center, Color.White, true);
  366. var style_Header = GetStyle(12, true, TextAlignmentType.Center, Color.FromArgb(153, 204, 0), false);
  367. //设置居中
  368. style.HorizontalAlignment = TextAlignmentType.Left;
  369. //行索引
  370. var rowIndex = 3;
  371. //列总数
  372. var colCount = dicItems == null ? properties.Length : dicItems.Keys.Count;
  373. //生成标题行
  374. cells.Merge(0, 0, 1, colCount);//合并单元格
  375. cells.Merge(1, 0, 1, colCount);//合并单元格
  376. cells[0, 0].PutValue(sFileName);//填写标题
  377. cells[1, 0].PutValue("匯出時間:" + DateTime.Now.ToString("yyyy/MM/dd"));//匯出時間
  378. SetCellsStyle(new int[] { 0, 0, 1, colCount }, 14, true, TextAlignmentType.Center, Color.White);//标题row樣式
  379. SetCellsStyle(new int[] { 1, 0, 1, colCount }, 12, false, TextAlignmentType.Right, Color.White);//時間row樣式
  380. cells.SetRowHeight(0, 25);
  381. cells.SetRowHeight(1, 20);
  382. //Header名的处理
  383. if (dicItems != null)
  384. {
  385. var index = 0;
  386. foreach (string sKey in dicItems.Keys)
  387. {
  388. var sValue = dicItems[sKey];
  389. if (sValue == null)
  390. {
  391. sValue = "";
  392. }
  393. cells[2, index].PutValue(sValue);//表頭
  394. cells[2, index].SetStyle(style_Header);//時間Header row樣式
  395. index++;
  396. }
  397. cells.SetRowHeight(2, 30);//设置行高
  398. }
  399. else
  400. {
  401. rowIndex--;
  402. }
  403. foreach (T entiy in list)
  404. {
  405. //填充資料
  406. if (dicItems != null)
  407. {
  408. var cellIndex = 0;
  409. foreach (string sKey in dicItems.Keys)
  410. {
  411. SetCells<T>(cells, entiy, sKey, dicAlain, style_C, style_L, style_R, rowIndex, ref cellIndex);
  412. }
  413. }
  414. else
  415. {
  416. var icol = 0;
  417. foreach (PropertyInfo property in properties)
  418. {
  419. SetCells<T>(cells, entiy, property.Name, dicAlain, style_C, style_L, style_R, rowIndex, ref icol);
  420. }
  421. }
  422. rowIndex++;
  423. }
  424. sheet.AutoFitColumns();
  425. sFilePath = Common.ConfigGetValue("", "OutFilesPath");
  426. sFileName = (sFileName ?? "") + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
  427. var sSeverPath = AppDomain.CurrentDomain.BaseDirectory + sFilePath;
  428. sFileFullName = sSeverPath + "/" + sFileName;
  429. Common.FnCreateDir(sSeverPath);
  430. workbook.Save(sFileFullName);
  431. bStatus = true;
  432. o_sFilePath = sFileFullName.Replace("\\", "/");
  433. return bStatus;
  434. }
  435. catch (Exception ex)
  436. {
  437. Logger.Error("导出文件时出错" + ex.Message, ex);
  438. o_sFilePath = "";
  439. return false;
  440. }
  441. }
  442. public RequestMessage Excel(RequestMessage i_crmInput)
  443. {
  444. RequestMessage crm = null;
  445. return crm;
  446. }
  447. /// <summary>
  448. /// 設置單元格樣式
  449. /// </summary>
  450. /// <param name="saPosition"></param>
  451. /// <param name="sFontSize"></param>
  452. /// <param name="bIsBold"></param>
  453. /// <param name="sAlign"></param>
  454. /// <param name="sBgColor"></param>
  455. private void SetCellsStyle(int[] saPosition, int sFontSize, bool bIsBold, TextAlignmentType sAlign, Color sBgColor)
  456. {
  457. var style = workbook.CreateStyle();
  458. var cells = sheet.Cells;
  459. var range = cells.CreateRange(saPosition[0], saPosition[1], saPosition[2], saPosition[3]);
  460. style.Font.Name = "宋体";//字體設置
  461. style.HorizontalAlignment = sAlign;//文字居左/中/右 ---TextAlignmentType.Center
  462. //style.Font.Color = Color.Blue;
  463. style.Font.Size = sFontSize;//文字大小 ----12
  464. style.Font.IsBold = bIsBold;//粗体 ----false
  465. style.ForegroundColor = sBgColor;//背景顏色
  466. style.Pattern = BackgroundType.Solid;//设置背景類型
  467. style.IsTextWrapped = true;//单元格内容自动换行
  468. // 邊線設置
  469. style.Borders[BorderType.TopBorder].LineStyle = CellBorderType.Thin;
  470. style.Borders[BorderType.LeftBorder].LineStyle = CellBorderType.Thin;
  471. style.Borders[BorderType.BottomBorder].LineStyle = CellBorderType.Thin;
  472. style.Borders[BorderType.RightBorder].LineStyle = CellBorderType.Thin;
  473. var flg = new StyleFlag() { All = true };
  474. range.ApplyStyle(style, flg);
  475. }
  476. /// <summary>
  477. /// 固定的樣式
  478. /// </summary>
  479. /// <param name="sFontSize"></param>
  480. /// <param name="bIsBold"></param>
  481. /// <param name="sAlign"></param>
  482. /// <param name="sBgColor"></param>
  483. /// <param name="bIsWrap"></param>
  484. /// <returns></returns>
  485. public Style GetStyle(int sFontSize, bool bIsBold, TextAlignmentType sAlign, Color sBgColor, bool bIsWrap)
  486. {
  487. var style = workbook.CreateStyle();
  488. style.HorizontalAlignment = sAlign;//文字居左/中/右 ---TextAlignmentType.Center
  489. //style.Font.Color = Color.Blue;
  490. if (sFontSize != 0)
  491. {
  492. style.Font.Size = sFontSize;//文字大小 ----12
  493. }
  494. style.Font.IsBold = bIsBold;//粗体 ----false
  495. style.ForegroundColor = sBgColor;//背景顏色
  496. style.Pattern = BackgroundType.Solid;//设置背景類型
  497. style.IsTextWrapped = bIsWrap;//单元格内容自动换行
  498. // 邊線設置
  499. style.Borders[BorderType.TopBorder].LineStyle = CellBorderType.Thin;
  500. style.Borders[BorderType.LeftBorder].LineStyle = CellBorderType.Thin;
  501. style.Borders[BorderType.BottomBorder].LineStyle = CellBorderType.Thin;
  502. style.Borders[BorderType.RightBorder].LineStyle = CellBorderType.Thin;
  503. return style;
  504. }
  505. /// <summary>
  506. /// </summary>
  507. /// <param name="sStart"></param>
  508. /// <param name="sEnd"></param>
  509. /// <param name="sColor"></param>
  510. private static void AddContainsStyle(string sStart, string sEnd, Color sColor)
  511. {
  512. //FormatConditionCollection conds = GetFormatCondition(sStart + ":" + sEnd, sColor);//LightSteelBlue
  513. //int idx = conds.AddCondition(FormatConditionType.CellValue);
  514. //FormatCondition cond = conds[idx];
  515. //cond.Style.Pattern = BackgroundType.Solid;
  516. //cond.Style.Borders[BorderType.LeftBorder].LineStyle = CellBorderType.Thin;
  517. //cond.Style.Borders[BorderType.RightBorder].LineStyle = CellBorderType.Thin;
  518. //cond.Style.Borders[BorderType.TopBorder].LineStyle = CellBorderType.Thin;
  519. //cond.Style.Borders[BorderType.BottomBorder].LineStyle = CellBorderType.Thin;
  520. }
  521. /// <summary>
  522. /// 設置分組header
  523. /// </summary>
  524. /// <param name="oCells"></param>
  525. /// <param name="oHeader"></param>
  526. /// <param name="o_oHeader"></param>
  527. private void SetGroupHeader(Cells oCells, object oHeader, out Dictionary<string, string> o_oHeader)
  528. {
  529. var dicHeader = new Dictionary<string, string>();
  530. var listHeader = oHeader as List<Dictionary<string, object>>;
  531. var iLastNO = 0;
  532. foreach (Dictionary<string, object> header in listHeader)
  533. {
  534. var _header = header["Header"] as Dictionary<string, string>;
  535. var sHeaderName = header["HeaderName"].ToString();
  536. var color = (Color)header["Color"];
  537. var style_Header = GetStyle(12, true, TextAlignmentType.Center, color, false);
  538. oCells.Merge(2, iLastNO, 1, _header.Keys.Count);//合并单元格
  539. oCells[2, iLastNO].PutValue(sHeaderName);//填写标题
  540. oCells[2, iLastNO].SetStyle(style_Header);//項次居中
  541. iLastNO += _header.Keys.Count;
  542. foreach (string key in _header.Keys)
  543. {
  544. dicHeader.Add(key, _header[key]);
  545. }
  546. }
  547. o_oHeader = dicHeader;
  548. }
  549. /// <summary>
  550. /// 設置header
  551. /// </summary>
  552. /// <param name="oCells"></param>
  553. /// <param name="dicHeader"></param>
  554. /// <param name="style_Header"></param>
  555. /// <param name="iRow"></param>
  556. private static void SetHeader(Cells oCells, Dictionary<string, string> dicHeader, Style style_Header, int iRow)
  557. {
  558. var index = 0;
  559. foreach (string sKey in dicHeader.Keys)
  560. {
  561. object sValue = dicHeader[sKey];
  562. if (sValue == null)
  563. {
  564. sValue = "";
  565. }
  566. oCells[iRow, index].PutValue(sValue);//表頭
  567. oCells[iRow, index].SetStyle(style_Header);//時間Header row樣式
  568. index++;
  569. }
  570. }
  571. /// <summary>
  572. /// </summary>
  573. /// <typeparam name="T"></typeparam>
  574. /// <param name="cells"></param>
  575. /// <param name="entiy"></param>
  576. /// <param name="name"></param>
  577. /// <param name="alains"></param>
  578. /// <param name="stylec"></param>
  579. /// <param name="stylel"></param>
  580. /// <param name="styler"></param>
  581. /// <param name="rowIndex"></param>
  582. /// <param name="index"></param>
  583. private static void SetCells<T>(Cells cells, T entiy, string name, Dictionary<string, string> alains, Style stylec, Style stylel, Style styler, int rowIndex, ref int index)
  584. {
  585. var sValue = ReflectionHelper.GetPropertyValue(entiy, name);
  586. var sType = ReflectionHelper.GetPropertyType(entiy, name);
  587. if (sValue == null)
  588. {
  589. sValue = "";
  590. }
  591. if (sType != null && sType.IndexOf("System.DateTime") > 0)
  592. {
  593. sValue = Convert.ToDateTime(sValue).ToString("yyyy/MM/dd HH:mm");
  594. }
  595. cells[rowIndex, index].PutValue(sValue);//表頭
  596. if (alains.Keys.Contains(name))
  597. {
  598. var sVal = alains[name].ToString();
  599. if (sVal == "center")
  600. {
  601. cells[rowIndex, index].SetStyle(stylec);//項次居中
  602. }
  603. else if (sVal == "right")
  604. {
  605. cells[rowIndex, index].SetStyle(styler);//項次居右
  606. }
  607. else
  608. {
  609. cells[rowIndex, index].SetStyle(stylel);//項次居左
  610. }
  611. }
  612. else
  613. {
  614. cells[rowIndex, index].SetStyle(stylel);//項次居左
  615. }
  616. index++;
  617. }
  618. // This method adds formatted conditions.
  619. private FormatConditionCollection GetFormatCondition(string cellAreaName, Color color)
  620. {
  621. // Adds an empty conditional formattings
  622. var index = sheet.ConditionalFormattings.Add();
  623. // Get the formatted conditions
  624. var formatConditions = sheet.ConditionalFormattings[index];
  625. // Get the cell area calling the custom GetCellAreaByName method
  626. var area = GetCellAreaByName(cellAreaName);
  627. // Add the formatted conditions cell area.
  628. formatConditions.AddArea(area);
  629. // Call the custom FillCell method
  630. FillCell(cellAreaName, color);
  631. // Return the formatted conditions
  632. return formatConditions;
  633. }
  634. // This method specifies the cell shading color for the conditional formattings cellarea range.
  635. private void FillCell(string cellAreaName, Color color)
  636. {
  637. var area = GetCellAreaByName(cellAreaName);
  638. var k = 0;
  639. for (int i = area.StartColumn; i <= area.EndColumn; i++)
  640. {
  641. for (int j = area.StartRow; j <= area.EndRow; j++)
  642. {
  643. var c = sheet.Cells[j, i];
  644. if (!color.IsEmpty)
  645. {
  646. var s = c.GetStyle();
  647. s.ForegroundColor = color;
  648. s.Pattern = BackgroundType.Solid;
  649. c.SetStyle(s);
  650. }
  651. // Set some random values to the cells in the cellarea range
  652. var value = j + i + k;
  653. c.PutValue(value);
  654. k++;
  655. }
  656. }
  657. }
  658. // This method specifies the CellArea range (start row, start col, end row, end col etc.) For
  659. // the conditional formatting
  660. internal static CellArea GetCellAreaByName(string s)
  661. {
  662. var area = new CellArea();
  663. var strCellRange = s.Replace("$", "").Split(':');
  664. CellsHelper.CellNameToIndex(strCellRange[0], out area.StartRow, out int column);
  665. area.StartColumn = column;
  666. if (strCellRange.Length == 1)
  667. {
  668. area.EndRow = area.StartRow;
  669. area.EndColumn = area.StartColumn;
  670. }
  671. else
  672. {
  673. CellsHelper.CellNameToIndex(strCellRange[1], out area.EndRow, out column);
  674. area.EndColumn = column;
  675. }
  676. return area;
  677. }
  678. private static void SetCellsWisth(int iCol, string sText, Dictionary<string, object> o_saItemsWidth)
  679. {
  680. double iWidth_New = 0;
  681. var c = sText.ToCharArray();
  682. for (int i = 0; i < c.Length; i++)
  683. {
  684. if (c[i] >= 0x4e00 && c[i] <= 0x9fbb)
  685. {
  686. iWidth_New += 2.5;
  687. }
  688. else
  689. {
  690. iWidth_New += 1.2;
  691. }
  692. }
  693. iWidth_New = iWidth_New > 50 ? 50 : iWidth_New;//最大給50
  694. if (o_saItemsWidth.Keys.Contains(iCol.ToString()))
  695. {
  696. foreach (string key in o_saItemsWidth.Keys)
  697. {
  698. if (key == iCol.ToString() && iWidth_New > double.Parse(o_saItemsWidth[key].ToString()))
  699. {
  700. o_saItemsWidth[key] = iWidth_New;
  701. break;
  702. }
  703. }
  704. }
  705. else
  706. {
  707. o_saItemsWidth.Add(iCol.ToString(), iWidth_New);
  708. }
  709. }
  710. public static Dictionary<string, string> GetExportAlain(object oHeader, object AlainCenter = null, object AlainRight = null)
  711. {
  712. var dicAlain = new Dictionary<string, string>();
  713. AlainCenter = AlainCenter ?? "";
  714. AlainRight = AlainRight ?? "";
  715. if (oHeader.GetType() == typeof(Dictionary<string, string>))
  716. {
  717. var dicHeader = oHeader as Dictionary<string, string>;
  718. PushAlain(dicHeader, AlainCenter, AlainRight, ref dicAlain);
  719. }
  720. else
  721. {
  722. var listHeader = oHeader as List<Dictionary<string, object>>;
  723. foreach (Dictionary<string, object> group in listHeader)
  724. {
  725. var dicCols = group["Header"] as Dictionary<string, string>;
  726. PushAlain(dicCols, AlainCenter, AlainRight, ref dicAlain);
  727. }
  728. }
  729. return dicAlain;
  730. }
  731. private static void PushAlain(Dictionary<string, string> cols, object AlainCenter, object AlainRight, ref Dictionary<string, string> dicAlain)
  732. {
  733. var saAlainCenter = new string[] { };
  734. var sAlainCenter = string.Empty;
  735. var saAlainRight = new string[] { };
  736. var sAlainRight = string.Empty;
  737. if (typeof(string) == AlainCenter.GetType())
  738. {
  739. sAlainCenter = AlainCenter.ToString();
  740. }
  741. else
  742. {
  743. saAlainCenter = AlainCenter as string[];
  744. }
  745. if (typeof(string) == AlainRight.GetType())
  746. {
  747. sAlainRight = AlainRight.ToString();
  748. }
  749. else
  750. {
  751. saAlainRight = AlainRight as string[];
  752. }
  753. foreach (string key in cols.Keys)
  754. {
  755. if (key == "RowIndex")
  756. {
  757. dicAlain.Add("RowIndex", "center");
  758. }
  759. else if (sAlainCenter.Contains(key) || saAlainCenter.Contains(key))
  760. {
  761. dicAlain.Add(key, "center");
  762. }
  763. else
  764. {
  765. if (sAlainRight.Contains(key) || saAlainRight.Contains(key))
  766. {
  767. dicAlain.Add(key, "right");
  768. }
  769. else
  770. {
  771. dicAlain.Add(key, "left");
  772. }
  773. }
  774. }
  775. }
  776. }
  777. }