ExportHelper.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. using Microsoft.Win32;
  2. using MuchInfo.Chart.Data.EnumTypes;
  3. using MuchInfo.Chart.Data.Interfaces;
  4. using NPOI.HSSF.Util;
  5. using NPOI.SS.UserModel;
  6. using NPOI.SS.Util;
  7. using NPOI.XSSF.UserModel;
  8. using System;
  9. using System.Collections.Generic;
  10. using System.ComponentModel;
  11. using System.IO;
  12. using System.Linq;
  13. namespace MuchInfo.Chart.WPF.Helpers
  14. {
  15. public delegate void ExportCompletedEventHandler(string message, string caption);
  16. public class ExportHelper
  17. {
  18. private string _sheetName;
  19. private List<ILineDataPoint> _dataPoints;
  20. private int _minUnit;
  21. private BackgroundWorker _backgroundWorker;
  22. private string _defaultName;
  23. public ExportCompletedEventHandler OnExportCompleted;
  24. public EventHandler OnStartExport;
  25. public void ExportToExcel(string goodsName, CycleType cycleType, List<ILineDataPoint> dataPoints, int minUnit)
  26. {
  27. if (string.IsNullOrWhiteSpace(goodsName)) return;
  28. if (dataPoints == null || !dataPoints.Any()) return;
  29. _minUnit = minUnit;
  30. _dataPoints = dataPoints;
  31. var startDate = dataPoints[0].Date.ToString("yyyyMMdd HHmm");
  32. var endDate = dataPoints[dataPoints.Count - 1].Date.ToString("yyyyMMdd HHmm");
  33. _sheetName = string.Format(LanguageManager.FindResource(LanguageConst.WorkSheetName), goodsName, GetCycleString(cycleType));
  34. _defaultName = _sheetName + "--(" + startDate + "-" + endDate + ")";
  35. //保存到文件
  36. var dialog = new SaveFileDialog
  37. {
  38. FileName = _defaultName,
  39. DefaultExt = ".xls",
  40. Filter = "Excel WorkSheet(.xls)|*.xls",
  41. };
  42. _backgroundWorker = new BackgroundWorker() { WorkerSupportsCancellation = true };
  43. _backgroundWorker.DoWork += BackgroundWorker_DoWork;
  44. _backgroundWorker.RunWorkerCompleted += BackgroundWorker_RunWorkerCompleted;
  45. var result = dialog.ShowDialog();
  46. if (OnStartExport != null)
  47. {
  48. OnStartExport(null, null);
  49. }
  50. if (result == true)
  51. {
  52. if (_backgroundWorker.IsBusy)
  53. {
  54. _backgroundWorker.CancelAsync();
  55. }
  56. else
  57. {
  58. _backgroundWorker.RunWorkerAsync(dialog.FileName);
  59. }
  60. }
  61. else
  62. {
  63. if (OnExportCompleted != null)
  64. {
  65. //message为空,只不弹出信息
  66. OnExportCompleted(string.Empty, string.Empty);
  67. }
  68. }
  69. }
  70. public void Dispose()
  71. {
  72. _dataPoints = null;
  73. if (_backgroundWorker != null)
  74. {
  75. _backgroundWorker.Dispose();
  76. _backgroundWorker = null;
  77. }
  78. }
  79. private void BackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
  80. {
  81. var caption = LanguageManager.FindResource(LanguageConst.ExportCaption);
  82. var message = LanguageManager.FindResource(LanguageConst.ExportSuccess);
  83. if (e.Error != null)
  84. message = LanguageManager.FindResource(LanguageConst.ExportFailed);
  85. else if (e.Cancelled)
  86. message = LanguageManager.FindResource(LanguageConst.ExportCancelled);
  87. if (OnExportCompleted != null)
  88. {
  89. OnExportCompleted(message + "[" + _sheetName + "]", caption);
  90. }
  91. this.Dispose();
  92. }
  93. private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
  94. {
  95. var fileName = e.Argument as string;
  96. if (string.IsNullOrWhiteSpace(fileName)) return;
  97. if (_dataPoints == null || !_dataPoints.Any()) return;
  98. //OfficeExport(fileName);
  99. NPOIExport(fileName);
  100. }
  101. /// <summary>
  102. /// Gets the cycle string.
  103. /// </summary>
  104. /// <param name="cycleType">Type of the cycle.</param>
  105. /// <returns>System.String.</returns>
  106. private string GetCycleString(CycleType cycleType)
  107. {
  108. switch (cycleType)
  109. {
  110. case CycleType.TimeSharing:
  111. return LanguageManager.FindResource(LanguageConst.TimeSpanControl_TimeSharingLine);
  112. case CycleType.Tik:
  113. return LanguageManager.FindResource(LanguageConst.TimeSpanControl_InstantLine);
  114. default:
  115. return cycleType.ToString();
  116. }
  117. }
  118. /// <summary>
  119. /// 导出excel文件
  120. /// </summary>
  121. /// <param name="fileName">Name of the file.</param>
  122. private void NPOIExport(string fileName)
  123. {
  124. var sw = File.OpenWrite(fileName);
  125. var workbook = new XSSFWorkbook();
  126. try
  127. {
  128. //设置表名长度为32
  129. var length = _sheetName.Length;
  130. var sheetName = _sheetName.Substring(0, length > 32 ? 32 : length);
  131. var sheet = workbook.CreateSheet(sheetName);
  132. var dataPoints = _dataPoints.OrderByDescending(z => z.Date).ToList();
  133. var upper = dataPoints.Count;
  134. //构建第一行
  135. var font1 = workbook.CreateFont();
  136. font1.Color = HSSFColor.RoyalBlue.Index;
  137. font1.Boldweight = (short)FontBoldWeight.Bold;
  138. font1.FontHeightInPoints = 14;
  139. var style1 = workbook.CreateCellStyle();
  140. style1.FillForegroundColor = HSSFColor.LightTurquoise.Index;
  141. style1.FillPattern = FillPattern.SolidForeground;
  142. style1.Alignment = HorizontalAlignment.Center;
  143. style1.VerticalAlignment = VerticalAlignment.Top;
  144. style1.SetFont(font1);
  145. var row1 = sheet.CreateRow(0);
  146. row1.Height = 2 * 256;
  147. var cell1 = row1.CreateCell(0);
  148. cell1.SetCellValue(_defaultName);
  149. sheet.AddMergedRegion(new CellRangeAddress(0, 0, 0, 4));
  150. cell1.CellStyle = style1;
  151. //构建第二行
  152. var font2 = workbook.CreateFont();
  153. font2.Color = HSSFColor.RoyalBlue.Index;
  154. font2.Boldweight = (short)FontBoldWeight.Bold;
  155. font2.FontHeightInPoints = 10;
  156. var style2 = workbook.CreateCellStyle();
  157. style2.FillForegroundColor = HSSFColor.LightYellow.Index;
  158. style2.FillPattern = FillPattern.SolidForeground;
  159. style2.Alignment = HorizontalAlignment.Center;
  160. style2.SetFont(font2);
  161. var row2 = sheet.CreateRow(1);
  162. var cell21 = row2.CreateCell(0);
  163. cell21.SetCellValue(LanguageManager.FindResource(LanguageConst.ExportDate));
  164. var cell22 = row2.CreateCell(1);
  165. cell22.SetCellValue(LanguageManager.FindResource(LanguageConst.Indicator_QuoteBoard_Open));
  166. var cell23 = row2.CreateCell(2);
  167. cell23.SetCellValue(LanguageManager.FindResource(LanguageConst.Indicator_QuoteBoard_High));
  168. var cell24 = row2.CreateCell(3);
  169. cell24.SetCellValue(LanguageManager.FindResource(LanguageConst.Indicator_QuoteBoard_Low));
  170. var cell25 = row2.CreateCell(4);
  171. cell25.SetCellValue(LanguageManager.FindResource(LanguageConst.Indicator_QuoteBoard_Close));
  172. cell21.CellStyle = style2;
  173. cell22.CellStyle = style2;
  174. cell23.CellStyle = style2;
  175. cell24.CellStyle = style2;
  176. cell25.CellStyle = style2;
  177. sheet.SetColumnWidth(0, 30 * 256);
  178. sheet.SetColumnWidth(1, 20 * 256);
  179. sheet.SetColumnWidth(2, 20 * 256);
  180. sheet.SetColumnWidth(3, 20 * 256);
  181. sheet.SetColumnWidth(4, 20 * 256);
  182. //var font3 = workbook.CreateFont();
  183. //font3.FontHeightInPoints = 10;
  184. //var style3 = workbook.CreateCellStyle();
  185. //style3.Alignment = HorizontalAlignment.Center;
  186. //style3.SetFont(font3);
  187. //填充数据
  188. for (int i = 0; i < upper; i++)
  189. {
  190. var point = dataPoints[i] as IOHLCDataPoint;
  191. if (point == null) continue;
  192. var row = sheet.CreateRow(2 + i);
  193. var cell31 = row.CreateCell(0);
  194. cell31.SetCellValue(point.Date.ToString());
  195. var cell32 = row.CreateCell(1);
  196. cell32.SetCellValue(TextFormatting.FormatNumber(point.Open, _minUnit, false));
  197. var cell33 = row.CreateCell(2);
  198. cell33.SetCellValue(TextFormatting.FormatNumber(point.High, _minUnit, false));
  199. var cell34 = row.CreateCell(3);
  200. cell34.SetCellValue(TextFormatting.FormatNumber(point.Low, _minUnit, false));
  201. var cell35 = row.CreateCell(4);
  202. cell35.SetCellValue(TextFormatting.FormatNumber(point.Close, _minUnit, false));
  203. //cell31.CellStyle = style3;
  204. //cell32.CellStyle = style3;
  205. //cell33.CellStyle = style3;
  206. //cell34.CellStyle = style3;
  207. //cell35.CellStyle = style3;
  208. }
  209. workbook.Write(sw);
  210. sw.Close();
  211. }
  212. finally
  213. {
  214. sw.Close();
  215. }
  216. }
  217. ///// <summary>
  218. ///// 必须安装office才能使用-放弃
  219. ///// </summary>
  220. ///// <param name="fileName">Name of the file.</param>
  221. //private void OfficeExport(string fileName)
  222. //{
  223. // var xApp = new Microsoft.Office.Interop.Excel.Application();
  224. // //创建工作簿(WorkBook:即Excel文件主体本身) 不能使用 new 来实例对象,不然会异常
  225. // var xBook = xApp.Workbooks.Add(Missing.Value);
  226. // try
  227. // {
  228. // //创建工作表(Worksheet:工作表,即Excel里的子表sheet)
  229. // var worksheet =
  230. // (Worksheet)xBook.Worksheets.Add(Missing.Value, Missing.Value, Missing.Value, Missing.Value);
  231. // //设置表名长度为32
  232. // var length = _sheetName.Length;
  233. // worksheet.Name = _sheetName.Substring(0, length > 32 ? 32 : length);
  234. // var dataPoints = _dataPoints.OrderByDescending(z => z.Date).ToList();
  235. // var upper = dataPoints.Count;
  236. // //构建第一行
  237. // var row1 = worksheet.Range[worksheet.Cells[1, 1], worksheet.Cells[1, 5]];
  238. // row1.MergeCells = true;
  239. // row1.Font.Size = 14;
  240. // row1.Font.Bold = true;
  241. // row1.Font.Color = Color.FromArgb(0, 120, 255);
  242. // row1.ColumnWidth = 100;
  243. // row1.RowHeight = 25;
  244. // row1.Cells.Interior.Color = Color.FromArgb(205, 255, 255);
  245. // row1.HorizontalAlignment = XlHAlign.xlHAlignCenter;
  246. // worksheet.Cells[1, 1] = _defaultName;
  247. // //构建第二行
  248. // var row2 = worksheet.Range[worksheet.Cells[2, 1], worksheet.Cells[2, 5]];
  249. // row2.HorizontalAlignment = XlHAlign.xlHAlignCenter;
  250. // row2.Cells.Interior.Color = Color.FromArgb(255, 255, 139);
  251. // row2.Font.Size = 10;
  252. // row2.Font.Bold = true;
  253. // row2.Font.Color = Color.FromArgb(0, 120, 255);
  254. // worksheet.Cells[2, 1] = LanguageManager.FindResource(LanguageConst.ExportDate);
  255. // worksheet.Cells[2, 2] = LanguageManager.FindResource(LanguageConst.Indicator_QuoteBoard_Open);
  256. // worksheet.Cells[2, 3] = LanguageManager.FindResource(LanguageConst.Indicator_QuoteBoard_High);
  257. // worksheet.Cells[2, 4] = LanguageManager.FindResource(LanguageConst.Indicator_QuoteBoard_Low);
  258. // worksheet.Cells[2, 5] = LanguageManager.FindResource(LanguageConst.Indicator_QuoteBoard_Close);
  259. // worksheet.Columns[1].ColumnWidth = 20;
  260. // worksheet.Columns[2].ColumnWidth = 20;
  261. // worksheet.Columns[3].ColumnWidth = 20;
  262. // worksheet.Columns[4].ColumnWidth = 20;
  263. // worksheet.Columns[5].ColumnWidth = 20;
  264. // //填充数据
  265. // for (int i = 0; i < upper; i++)
  266. // {
  267. // var point = dataPoints[i] as IOHLCDataPoint;
  268. // if (point == null) continue;
  269. // var row3 = worksheet.Range[worksheet.Cells[i + 3, 1], worksheet.Cells[i + 3, 5]];
  270. // row3.Font.Size = 10;
  271. // worksheet.Cells[i + 3, 1] = point.Date;
  272. // worksheet.Cells[i + 3, 2] = TextFormatting.FormatNumber(point.Open, _minUnit, false);
  273. // worksheet.Cells[i + 3, 3] = TextFormatting.FormatNumber(point.High, _minUnit, false);
  274. // worksheet.Cells[i + 3, 4] = TextFormatting.FormatNumber(point.Low, _minUnit, false);
  275. // worksheet.Cells[i + 3, 5] = TextFormatting.FormatNumber(point.Close, _minUnit, false);
  276. // }
  277. // xBook.SaveAs(fileName, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value,
  278. // XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value, Missing.Value,
  279. // Missing.Value);
  280. // }
  281. // finally
  282. // {
  283. // xBook.Close(Missing.Value, Missing.Value, Missing.Value);
  284. // xApp.Workbooks.Close();
  285. // xApp.Quit();
  286. // // 强制回收 Excel 进程
  287. // int geneID = System.GC.GetGeneration(xApp);
  288. // xBook = null;
  289. // xApp = null;
  290. // System.GC.Collect(geneID);
  291. // GC.Collect();
  292. // }
  293. //}
  294. }
  295. }