OfficeFileHandleHelper.cs 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Windows.Forms;
  5. using System.Runtime.InteropServices;
  6. using Microsoft.Office.Interop.Excel;
  7. using System.Reflection;
  8. using Microsoft.Office.Core;
  9. namespace SmartCoalApplication.Base.CommTool
  10. {
  11. /// <summary>
  12. /// excel操作类
  13. /// </summary>
  14. public static class OfficeFileHandleHelper
  15. {
  16. private static Microsoft.Office.Interop.Excel.Application m_excel;
  17. private static Workbook m_workbook;
  18. private static Worksheet m_worksheet;
  19. private static Worksheet m2_worksheet;
  20. private static object missing = Type.Missing;
  21. /// <summary>
  22. /// 打开word和excel文档
  23. /// </summary>
  24. /// <param name="filePath"></param>
  25. public static bool OpenOfficeFile(string filePath)
  26. {
  27. bool isSucceed = false;//打开是否成功
  28. int fileType = FileOperationHelper.IsFileWordOrExcel(filePath);
  29. try
  30. {
  31. m_excel = new Microsoft.Office.Interop.Excel.Application();
  32. m_excel.Workbooks.Open(filePath);
  33. m_excel.Visible = true;
  34. isSucceed = true;
  35. }
  36. catch (Exception)
  37. {
  38. if (m_excel != null)
  39. {
  40. m_excel.DisplayAlerts = false;
  41. m_excel.Visible = false;
  42. }
  43. isSucceed = false;
  44. }
  45. m_excel = null;
  46. //其他
  47. return isSucceed;
  48. }
  49. /// <summary>
  50. /// 通过公式模板创建并保存excel
  51. /// </summary>
  52. /// <param name="excelModulePath">excel公式模板路径</param>
  53. /// <param name="saveAsPath">新文件另存路径</param>
  54. /// <param name="contentList">数据对象模型</param>
  55. /// <returns></returns>
  56. public static bool SaveAsExcelWithModule(string excelModulePath, string saveAsPath, List<List<string>> contentList, string dictPath = null, Dictionary<string, string> pNames = null
  57. , List<List<string>> content2List = null)
  58. {
  59. try
  60. {
  61. m_excel = new Microsoft.Office.Interop.Excel.Application();
  62. m_workbook = m_excel.Workbooks.Add(excelModulePath);
  63. m_worksheet = m_workbook.Sheets.Item[2];//数据固定插入在第二个sheet页
  64. Worksheet m_worksheet1 = m_workbook.Sheets.Item[1];//数据固定插入在第二个sheet页
  65. if (content2List != null)
  66. {
  67. if (m_workbook.Sheets.Count < 3)
  68. m_workbook.Sheets.Add(Missing.Value, m_worksheet, Missing.Value, Missing.Value);
  69. m2_worksheet = m_workbook.Sheets.Item[3];
  70. AddTableToExcelSheet(m2_worksheet, 1, 1, content2List);
  71. }
  72. if (dictPath != null)
  73. {
  74. Microsoft.Office.Interop.Excel.Pictures pics = (Microsoft.Office.Interop.Excel.Pictures)m_worksheet1.Pictures(Type.Missing);
  75. Dictionary<string, Microsoft.Office.Interop.Excel.Range> keyValuePairs = new Dictionary<string, Range>();
  76. for (int i = 1; i <= pics.Count; i++)
  77. {
  78. //可以循环这个excel里面的图
  79. Picture pic = pics.Item(i) as Picture;
  80. //可以获取图的左上cell
  81. Range topleft = pic.TopLeftCell;
  82. //可以获取图的右下cell
  83. Range rightbottom = pic.BottomRightCell;
  84. keyValuePairs.Add(pic.Name, m_worksheet1.get_Range(topleft, rightbottom));
  85. }
  86. pics.Delete();
  87. foreach (string d in Directory.GetFileSystemEntries(dictPath))
  88. {
  89. string pName = d.Replace(dictPath + "\\", string.Empty);
  90. string pName1 = pName.Replace(".jpg", string.Empty);
  91. Microsoft.Office.Interop.Excel.Range range;
  92. keyValuePairs.TryGetValue(pName1, out range);
  93. if (range != null)
  94. InsertPicture(range, m_worksheet1, d, dictPath, pNames);
  95. }
  96. }
  97. AddTableToExcelSheet(m_worksheet, 1, 1, contentList);
  98. //if (content2List != null)
  99. // ((Worksheet)m_workbook.Sheets.Item[2]).Select();
  100. m_worksheet.SaveAs(saveAsPath, missing, missing, missing, missing, missing, missing, missing, missing, missing);
  101. m_workbook.Close(false);
  102. m_excel.Application.Quit();
  103. Kill(m_excel);
  104. m_worksheet = null;
  105. m2_worksheet = null;
  106. m_workbook = null;
  107. m_excel = null;
  108. }
  109. catch (Exception)
  110. {
  111. if (m_excel != null)
  112. {
  113. if (m_workbook != null)
  114. m_workbook.Close(false);
  115. m_excel.Application.Quit();
  116. Kill(m_excel);
  117. }
  118. m_worksheet = null;
  119. m2_worksheet = null;
  120. m_workbook = null;
  121. m_excel = null;
  122. return false;
  123. }
  124. return true;
  125. }
  126. /// 将图片插入到指定的单元格位置,并设置图片的宽度和高度。
  127. /// 注意:图片必须是绝对物理路径
  128. /// </summary>
  129. /// <param name="rng">Excel单元格选中的区域</param>
  130. /// <param name="PicturePath">要插入图片的绝对路径。</param>
  131. public static void InsertPicture(Microsoft.Office.Interop.Excel.Range rng, Microsoft.Office.Interop.Excel._Worksheet sheet, string PicturePath, string dictPath, Dictionary<string, string> pNames)
  132. {
  133. //rng.Select();
  134. float PicLeft, PicTop, PicWidth, PicHeight;
  135. try
  136. {
  137. PicLeft = Convert.ToSingle(rng.Left);
  138. PicTop = Convert.ToSingle(rng.Top);
  139. PicWidth = Convert.ToSingle(rng.Width);
  140. PicHeight = Convert.ToSingle(rng.Height);
  141. sheet.Shapes.AddPicture(PicturePath, MsoTriState.msoFalse, MsoTriState.msoTrue, PicLeft, PicTop, PicWidth, PicHeight);
  142. Microsoft.Office.Interop.Excel.Pictures pics = (Microsoft.Office.Interop.Excel.Pictures)sheet.Pictures(Type.Missing);
  143. string pName = PicturePath.Replace(dictPath + "\\", string.Empty);
  144. string pName1 = pName.Replace(".jpg", string.Empty);
  145. if (pics.Count > 0)
  146. {
  147. Picture pic = pics.Item(pics.Count) as Picture;
  148. string pName2;
  149. pNames.TryGetValue(pName1, out pName2);
  150. pic.Name = pName2;
  151. }
  152. }
  153. catch (Exception ex)
  154. {
  155. MessageBox.Show("错误:" + ex.Message);
  156. }
  157. }
  158. /// <summary>
  159. /// 向excel的sheet页指定单元格插入表格(自行拼接的list形式)
  160. /// </summary>
  161. /// <param name="worksheet">sheet页</param>
  162. /// <param name="x">插入初始位置横坐标</param>
  163. /// <param name="y">插入初始位置纵坐标</param>
  164. /// <param name="contentList">表格对象</param>
  165. public static void AddTableToExcelSheet(Worksheet worksheet, int x, int y, List<List<string>> contentList)
  166. {
  167. if (contentList.Count > 0)
  168. {
  169. for (int i = x; i < contentList.Count + 1; i++)
  170. {
  171. List<string> rowContent = contentList[i - 1];
  172. if (rowContent.Count > 0)
  173. {
  174. for (int j = y; j < rowContent.Count + 1; j++)
  175. {
  176. worksheet.Cells[i, j] = rowContent[j - 1];
  177. }
  178. }
  179. }
  180. }
  181. }
  182. /// <summary>
  183. /// 杀死进程
  184. /// </summary>
  185. /// <param name="hwnd"></param>
  186. /// <param name="ID"></param>
  187. /// <returns></returns>
  188. [DllImport("User32.dll", CharSet = CharSet.Auto)]
  189. public static extern int GetWindowThreadProcessId(IntPtr hwnd, out int ID);
  190. public static void Kill(Microsoft.Office.Interop.Excel.Application excel)
  191. {
  192. IntPtr t = new IntPtr(excel.Hwnd); //得到这个句柄,具体作用是得到这块内存入口
  193. int k = 0;
  194. GetWindowThreadProcessId(t, out k); //得到本进程唯一标志k
  195. System.Diagnostics.Process p = System.Diagnostics.Process.GetProcessById(k); //得到对进程k的引用
  196. p.Kill(); //关闭进程k
  197. }
  198. }
  199. }