OfficeFileOperater.cs 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382
  1. using System;
  2. using System.Collections.Generic;
  3. using MSWord = Microsoft.Office.Interop.Word;
  4. using MSExcel = Microsoft.Office.Interop.Excel;
  5. using System.IO;
  6. using PaintDotNet.Base.Functionodel;
  7. using System.Windows.Forms;
  8. using System.Runtime.InteropServices;
  9. using System.Drawing;
  10. using System.Text.RegularExpressions;
  11. using Microsoft.Office.Interop.Excel;
  12. using System.Reflection;
  13. using Microsoft.Office.Core;
  14. using PaintDotNet.Base.CommTool;
  15. namespace Metis.AutoAnalysis
  16. {
  17. /// <summary>
  18. /// word和excel操作类
  19. /// </summary>
  20. public static class OfficeFileOperater
  21. {
  22. private static Object missing = Type.Missing;
  23. private static MSWord.Application m_word;
  24. private static MSWord.Document m_doc;
  25. private static MSExcel.Application m_excel;
  26. private static MSExcel.Workbook m_workbook;
  27. private static MSExcel.Worksheet m_worksheet;
  28. private static MSExcel.Worksheet m3_worksheet;
  29. private static MSExcel.Worksheet m2_worksheet;
  30. public static System.Data.DataTable calipersTable; //颗粒统计-卡规设置
  31. /// <summary>
  32. /// 打开word和excel文档
  33. /// </summary>
  34. /// <param name="filePath"></param>
  35. public static bool OpenOfficeFile(string filePath)
  36. {
  37. bool isSucceed = false;//打开是否成功
  38. int fileType = FileOperationHelper.IsFileWordOrExcel(filePath);
  39. //word文档
  40. if (fileType == 1)
  41. {
  42. try
  43. {
  44. m_word = new MSWord.Application();
  45. Object fileName = filePath;
  46. m_word.Documents.Open(ref fileName,
  47. ref missing, ref missing, ref missing, ref missing, ref missing,
  48. ref missing, ref missing, ref missing, ref missing, ref missing,
  49. ref missing, ref missing, ref missing, ref missing, ref missing);
  50. m_word.Visible = true;
  51. isSucceed = true;
  52. m_word = null;
  53. }
  54. catch (Exception)
  55. {
  56. //如果文件之前已打开,且拒绝再次使用只读模式打开
  57. //属于打开文件失败,但word程序已创建,将该程序关闭
  58. if(m_word != null)
  59. {
  60. m_word.Visible = false;
  61. m_word.Quit(false, ref missing, ref missing);
  62. m_word = null;
  63. }
  64. //用户手动取消"打开已打开文件的副本",会进入该判断
  65. //if (e.Message == "命令失败")
  66. // return true;
  67. isSucceed = false;
  68. }
  69. }
  70. //excel文档
  71. else if (fileType == 2)
  72. {
  73. try
  74. {
  75. m_excel = new MSExcel.Application();
  76. m_excel.Workbooks.Open(filePath);
  77. m_excel.Visible = true;
  78. isSucceed = true;
  79. }
  80. catch (Exception)
  81. {
  82. if (m_excel != null)
  83. {
  84. m_excel.DisplayAlerts = false;
  85. m_excel.Visible = false;
  86. }
  87. isSucceed = false;
  88. }
  89. m_excel = null;
  90. }
  91. //其他
  92. else
  93. {
  94. }
  95. return isSucceed;
  96. }
  97. /// <summary>
  98. /// 新建空白word文档
  99. /// </summary>
  100. /// <param name="dictPath">保存路径</param>
  101. /// <param name="filePath">文件全路径</param>
  102. /// <param name="opened">是否自动打开</param>
  103. /// <returns></returns>
  104. public static bool CreateNewWordFile(string dictPath, string filePath, bool isOpened)
  105. {
  106. //路径不存在则创建
  107. if (!Directory.Exists(dictPath))
  108. Directory.CreateDirectory(dictPath);
  109. try
  110. {
  111. m_word = new MSWord.Application();
  112. Object savePath = filePath;
  113. m_doc = m_word.Documents.Add(ref missing, ref missing, ref missing, ref missing);
  114. m_doc.SaveAs2(ref savePath,
  115. ref missing, ref missing, ref missing, ref missing, ref missing,
  116. ref missing, ref missing, ref missing, ref missing, ref missing,
  117. ref missing, ref missing, ref missing, ref missing, ref missing);
  118. if (isOpened)
  119. m_word.Visible = true;//画面上是否可见
  120. else
  121. {
  122. m_doc.Close(false, ref missing, ref missing);
  123. m_word.Quit(false, ref missing, ref missing);
  124. }
  125. m_word = null;
  126. m_doc = null;
  127. return true;
  128. }
  129. catch(Exception)
  130. {
  131. if(m_word != null)
  132. {
  133. if(m_doc != null)
  134. {
  135. m_doc.Close(false, ref missing, ref missing);
  136. m_doc = null;
  137. }
  138. m_word.Visible = false;
  139. m_word.Quit(false, ref missing, ref missing);
  140. m_word = null;
  141. }
  142. return false;
  143. }
  144. }
  145. /// <summary>
  146. /// 新建空白excel文档
  147. /// </summary>
  148. /// <param name="dictPath">保存路径</param>
  149. /// <param name="filePath">文件全路径</param>
  150. /// <param name="opened">是否自动打开</param>
  151. /// <returns></returns>
  152. public static bool CreateNewExcelFile(string dictPath, string filePath, bool isOpened)
  153. {
  154. //路径不存在则创建
  155. if (!Directory.Exists(dictPath))
  156. Directory.CreateDirectory(dictPath);
  157. try
  158. {
  159. m_excel = new MSExcel.Application();
  160. m_workbook = m_excel.Workbooks.Add(true);
  161. for (int i = 0; i < 2; i++)
  162. {
  163. m_workbook.Worksheets.Add(After: m_workbook.Sheets.get_Item(m_workbook.Sheets.Count));
  164. }
  165. m_workbook.SaveAs(filePath, missing, missing, missing, missing, missing, MSExcel.XlSaveAsAccessMode.xlExclusive, missing, missing, missing);
  166. }
  167. catch (Exception e)
  168. {
  169. throw e;
  170. }
  171. finally
  172. {
  173. if (m_excel != null)
  174. {
  175. if (m_workbook != null)
  176. m_workbook.Close(false);
  177. m_excel.Application.Quit();
  178. Kill(m_excel);
  179. }
  180. m_worksheet = null;
  181. m_workbook = null;
  182. m_excel = null;
  183. }
  184. return true;
  185. }
  186. #region 新的分析报告通用方法-word中的图片定倍显示
  187. /// <summary>
  188. /// 生成分析报告
  189. /// </summary>
  190. /// <param name="analyzeSettingModel">基础信息对象</param>
  191. /// <param name="contentList">数据对象模型</param>
  192. /// <param name="bitmapList">图片集合</param>
  193. /// <param name="tagPositionDic">除基础信息外的word书签与excel坐标对应信息</param>
  194. /// <param name="pointPitch">当前图片放大倍数</param>
  195. /// <param name="unitLength">当前图片标尺</param>
  196. /// <param name="gainMultiple">系统激活放大倍数(暂时不用保留)</param>
  197. public static void CreateAnalysisReport(AutoAnalyzeSettingModel analyzeSettingModel, List<List<string>> contentList, List<Bitmap> bitmapList,
  198. Dictionary<string, string> tagPositionDic, bool isNeedZoom, double pointPitch, double unitLength, decimal gainMultiple, string lblResult, string dictPath = null, Dictionary<string, string> pNames = null, List<List<string>> content2List = null)
  199. {
  200. string saveAsPath = "";
  201. string excelModulePath = Path.GetDirectoryName(analyzeSettingModel.modulePath) + "\\公式.xlsx";//获取excel公式模板的路径
  202. if (File.Exists(excelModulePath))
  203. {
  204. saveAsPath = analyzeSettingModel.savePath + "\\" + analyzeSettingModel.analyzeClassify //+ "分析"
  205. + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx";//另存的excel文件名
  206. //如果savePath是盘符不是文件夹,会多出一个斜杠,office的saveas无法识别,固需处理一下
  207. if (saveAsPath.IndexOf("\\\\") != -1)
  208. saveAsPath = saveAsPath.Replace("\\\\", "\\");
  209. if (contentList != null)
  210. {
  211. SaveAsExcelWithModule(excelModulePath, saveAsPath, contentList, dictPath, pNames, content2List);
  212. }
  213. Dictionary<string, string> tagValueDic = GetContentFromExcel(saveAsPath, tagPositionDic);
  214. CreateNewWordWithContent(analyzeSettingModel, tagValueDic, bitmapList, pointPitch, unitLength, gainMultiple,lblResult);
  215. }
  216. }
  217. /// <summary>
  218. /// 生成分析报告并保存图片与中间数据
  219. /// </summary>
  220. /// <param name="analyzeSettingModel"></param>
  221. /// <param name="contentList"></param>
  222. /// <param name="dataList">中间数据</param>
  223. /// <param name="bitmapList"></param>
  224. /// <param name="tagPositionDic"></param>
  225. /// <param name="newPath"></param>
  226. /// <param name="newCode"></param>
  227. public static void CreateAnalysisReport(AnalyzeSettingModel analyzeSettingModel, List<List<string>> contentList, List<ExportProjectModel> dataList,
  228. List<Bitmap> bitmapList, Dictionary<string, string> tagPositionDic, string newPath, string newCode, bool isNeedZoom, double pointPitch, double unitLength, decimal gainMultiple, string dictPath, Dictionary<string, string> pNames, List<List<string>> content2List)
  229. {
  230. string saveAsPath = "";
  231. string excelModulePath = Path.GetDirectoryName(analyzeSettingModel.modulePath) + "\\公式.xlsx";//获取excel公式模板的路径
  232. if (File.Exists(excelModulePath))
  233. {
  234. saveAsPath = newPath + "\\" + newCode + ".xlsx";//另存的excel文件名
  235. //如果savePath是盘符不是文件夹,会多出一个斜杠,office的saveas无法识别,固需处理一下
  236. if (saveAsPath.IndexOf("\\\\") != -1)
  237. saveAsPath = saveAsPath.Replace("\\\\", "\\");
  238. if (SaveAsExcelWithModule(excelModulePath, saveAsPath, contentList, dictPath, pNames, content2List))
  239. {
  240. //保存中间数据
  241. string tempDataPath = newPath + "\\" + newCode + "_1.xlsx"; //"-中间数据" + ".xlsx";
  242. if (tempDataPath.IndexOf("\\\\") != -1)
  243. tempDataPath = tempDataPath.Replace("\\\\", "\\");
  244. SaveTempDataToExcel(tempDataPath, dataList);
  245. Dictionary<string, string> tagValueDic = GetContentFromExcel(saveAsPath, tagPositionDic);
  246. //if (isNeedZoom)
  247. //{
  248. // List<Bitmap> zoomList = new List<Bitmap>();
  249. // for (int i = 0; i < bitmapList.Count; i++)
  250. // {
  251. // zoomList.Add(GetFixedMultipleBitmap(bitmapList[i], pointPitch, unitLength, gainMultiple));
  252. // }
  253. // CreateNewWordWithContent(analyzeSettingModel, tagValueDic, zoomList, newPath, newCode);
  254. //}
  255. //else
  256. //{
  257. // CreateNewWordWithContent(analyzeSettingModel, tagValueDic, bitmapList, newPath, newCode);
  258. //}
  259. CreateNewWordWithContent(analyzeSettingModel, tagValueDic, bitmapList, newPath, newCode);
  260. //保存图片
  261. SaveAllImage(bitmapList, newPath, newCode);
  262. }
  263. }
  264. }
  265. /// <summary>
  266. /// 返回定倍(A4纸)显示后的图片
  267. /// 定倍计算公式:图片像素(宽和高) * 当前图片标尺 * 当前图片放大倍数
  268. /// </summary>
  269. /// <param name="oldBit"></param>
  270. /// <param name="pointPitch">当前图片放大倍数</param>
  271. /// <param name="unitLength">当前图片标尺</param>
  272. /// <param name="gainMultiple">系统激活标尺放大倍数(暂时没用)</param>
  273. /// <returns></returns>
  274. private static Bitmap GetFixedMultipleBitmap(Bitmap oldBit, double pointPitch, double unitLength, decimal gainMultiple)
  275. {
  276. if (pointPitch == 0)
  277. return oldBit;
  278. int oldWidth = oldBit.Width;
  279. int oldHeight = oldBit.Height;
  280. int targetWidth = 0;
  281. int targetHeight = 0;
  282. if (oldWidth <= 1 || oldHeight <= 1)//像素最小为1,之后不再处理
  283. return oldBit;
  284. //点距定倍注释
  285. //double pantographRatio = unitLength / pointPitch;//缩放比
  286. //double pantographRatio = unitLength * (double)gainMultiple;//标尺*放大倍数
  287. //double aspectRatio = oldWidth / (oldHeight * 1d);//宽高比
  288. //if (oldWidth <= oldHeight)
  289. //{
  290. // //targetWidth = (int)(oldWidth * pantographRatio * (double)gainMultiple);
  291. // // 定倍(A4)计算公式:图片像素(宽) * 当前图片标尺 * 当前图片放大倍数
  292. // targetWidth = (int)(oldWidth * pantographRatio) ;
  293. // if (targetWidth < 1 || targetWidth > oldWidth)//像素值异常不做处理
  294. // return oldBit;
  295. // targetHeight = (int)(targetWidth / aspectRatio);
  296. //}
  297. //else
  298. //{
  299. // //点距定倍注释
  300. // //targetHeight = (int)(oldHeight * pantographRatio * (double)gainMultiple);
  301. // // 定倍(A4)计算公式:图片像素(高) * 当前图片标尺 * 当前图片放大倍数
  302. // targetHeight = (int)(oldHeight * pantographRatio);
  303. // if (targetHeight < 1 || targetHeight > oldHeight)//像素值异常不做处理
  304. // return oldBit;
  305. // targetWidth = (int)(targetHeight * aspectRatio);
  306. //}
  307. //缩放图片
  308. Bitmap targetBit = new Bitmap(oldWidth, oldHeight);
  309. Graphics g = Graphics.FromImage(targetBit);
  310. g.DrawImage(oldBit, new System.Drawing.Rectangle(0, 0, oldWidth, oldHeight), new System.Drawing.Rectangle(0, 0, oldWidth, oldHeight), GraphicsUnit.Pixel);
  311. return targetBit;
  312. }
  313. #endregion
  314. private static string NunToChar(int number)
  315. {
  316. if (65 <= number && 90 >= number)
  317. {
  318. System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();
  319. byte[] btNumber = new byte[] { (byte)number };
  320. return asciiEncoding.GetString(btNumber);
  321. }
  322. return "数字不在转换范围内";
  323. }
  324. /// 将图片插入到指定的单元格位置,并设置图片的宽度和高度。
  325. /// 注意:图片必须是绝对物理路径
  326. /// </summary>
  327. /// <param name="rng">Excel单元格选中的区域</param>
  328. /// <param name="PicturePath">要插入图片的绝对路径。</param>
  329. public static void InsertPicture(RectangleF rng, Microsoft.Office.Interop.Excel._Worksheet sheet, string PicturePath, string dictPath, Dictionary<string, string> pNames)
  330. {
  331. //rng.Select();
  332. float PicLeft, PicTop, PicWidth, PicHeight;
  333. try
  334. {
  335. PicLeft = rng.Left;// Convert.ToSingle(rng.Left);
  336. PicTop = rng.Top;// Convert.ToSingle(rng.Top);
  337. PicWidth = rng.Width;// Convert.ToSingle(rng.Width);
  338. PicHeight = rng.Height;// Convert.ToSingle(rng.Height);
  339. sheet.Shapes.AddPicture(PicturePath, MsoTriState.msoFalse, MsoTriState.msoTrue, PicLeft, PicTop, PicWidth, PicHeight);
  340. Microsoft.Office.Interop.Excel.Pictures pics = (Microsoft.Office.Interop.Excel.Pictures)sheet.Pictures(Type.Missing);
  341. string pName = PicturePath.Replace(dictPath + "\\", string.Empty);
  342. string pName1 = pName.Replace(".jpg", string.Empty);
  343. if (pics.Count > 0)
  344. {
  345. Picture pic = pics.Item(pics.Count) as Picture;
  346. string pName2;
  347. pNames.TryGetValue(pName1, out pName2);
  348. pic.Name = pName2;
  349. }
  350. }
  351. catch (Exception ex)
  352. {
  353. MessageBox.Show("错误:" + ex.Message);
  354. }
  355. }
  356. /// <summary>
  357. /// 通过公式模板创建并保存excel
  358. /// </summary>
  359. /// <param name="excelModulePath">excel公式模板路径</param>
  360. /// <param name="saveAsPath">新文件另存路径</param>
  361. /// <param name="contentList">数据对象模型</param>
  362. /// <returns></returns>
  363. public static bool SaveAsExcelWithModule(string excelModulePath, string saveAsPath, List<List<string>> contentList, string dictPath = null, Dictionary<string, string> pNames = null
  364. , List<List<string>> content2List = null)
  365. {
  366. try
  367. {
  368. m_excel = new MSExcel.Application();
  369. m_workbook = m_excel.Workbooks.Add(excelModulePath);
  370. m_worksheet = m_workbook.Sheets.Item[2];//数据固定插入在第二个sheet页
  371. MSExcel.Worksheet m_worksheet1 = m_workbook.Sheets.Item[1];//数据固定插入在第二个sheet页
  372. if (content2List != null)
  373. {
  374. if (m_workbook.Sheets.Count < 3)
  375. m_workbook.Sheets.Add(Missing.Value, m_worksheet, Missing.Value, Missing.Value);
  376. m2_worksheet = m_workbook.Sheets.Item[3];
  377. AddTableToExcelSheet(m2_worksheet, 1, 1, content2List);
  378. }
  379. if (dictPath != null)
  380. {
  381. Microsoft.Office.Interop.Excel.Pictures pics = (Microsoft.Office.Interop.Excel.Pictures)m_worksheet1.Pictures(Type.Missing);
  382. Dictionary<string, RectangleF> keyValuePairs = new Dictionary<string, RectangleF>();
  383. for (int i = 1; i <= pics.Count; i++)
  384. {
  385. //可以循环这个excel里面的图
  386. Picture pic = pics.Item(i) as Picture;
  387. ////可以获取图的左上cell
  388. //Range topleft = pic.Left;
  389. ////可以获取图的右下cell
  390. //Range rightbottom = pic.BottomRightCell;
  391. keyValuePairs.Add(pic.Name, new RectangleF((float)pic.Left, (float)pic.Top, (float)pic.Width, (float)pic.Height)/*m_worksheet1.get_Range(topleft, rightbottom)*/);
  392. }
  393. pics.Delete();
  394. foreach (string d in Directory.GetFileSystemEntries(dictPath))
  395. {
  396. string pName = d.Replace(dictPath + "\\", string.Empty);
  397. string pName1 = pName.Replace(".jpg", string.Empty);
  398. RectangleF/*Microsoft.Office.Interop.Excel.Range*/ range;
  399. keyValuePairs.TryGetValue(pName1, out range);
  400. if (range != null)
  401. InsertPicture(range, m_worksheet1, d, dictPath, pNames);
  402. }
  403. }
  404. if (calipersTable != null)
  405. {
  406. if (m_workbook.Sheets.Count < 3)
  407. m_workbook.Sheets.Add(Missing.Value, m_worksheet, Missing.Value, Missing.Value);
  408. m3_worksheet = m_workbook.Sheets.Item[3];
  409. m3_worksheet.Name = "feret all";
  410. AddExportCalipersSheet(m3_worksheet, calipersTable);
  411. calipersTable = null;
  412. }
  413. AddTableToExcelSheet(m_worksheet, 1, 1, contentList);
  414. //if (content2List != null)
  415. // ((Worksheet)m_workbook.Sheets.Item[2]).Select();
  416. m_worksheet.SaveAs(saveAsPath, missing, missing, missing, missing, missing, missing, missing, missing, missing);
  417. //m_worksheet.Activate();
  418. m_workbook.Close(false);
  419. m_excel.Application.Quit();
  420. Kill(m_excel);
  421. m_worksheet = null;
  422. m2_worksheet = null;
  423. m_workbook = null;
  424. m_excel = null;
  425. }
  426. catch (Exception)
  427. {
  428. if (m_excel != null)
  429. {
  430. if (m_workbook != null)
  431. m_workbook.Close(false);
  432. m_excel.Application.Quit();
  433. Kill(m_excel);
  434. }
  435. m_worksheet = null;
  436. m2_worksheet = null;
  437. m_workbook = null;
  438. m_excel = null;
  439. return false;
  440. }
  441. return true;
  442. }
  443. /// <summary>
  444. /// 保存中间数据excel
  445. /// </summary>
  446. /// <param name="savePath"></param>
  447. /// <param name="dataList"></param>
  448. /// <returns></returns>
  449. public static bool SaveTempDataToExcel(string savePath, List<ExportProjectModel> dataList)
  450. {
  451. if (dataList != null && dataList.Count > 0)
  452. {
  453. dataList.Reverse();
  454. try
  455. {
  456. m_excel = new MSExcel.Application();
  457. m_workbook = m_excel.Workbooks.Add(true);
  458. int sheetIndex = 0;
  459. foreach (ExportProjectModel model in dataList)
  460. {
  461. if (sheetIndex != 0)
  462. m_workbook.Sheets.Add();
  463. m_worksheet = m_workbook.Sheets.Item[1];
  464. //去掉名称的后缀,不然为sheet页命名会报错
  465. string worksheetName = model.picName;
  466. if (worksheetName.LastIndexOf(".") != -1)
  467. worksheetName = worksheetName.Remove(worksheetName.LastIndexOf("."));
  468. //捕获异常,设置sheet页命名太长等原因可能会报错
  469. Exception nameLengthExceed;
  470. do
  471. {
  472. try
  473. {
  474. nameLengthExceed = null;
  475. m_worksheet.Name = worksheetName;
  476. }
  477. catch (Exception e)
  478. {
  479. nameLengthExceed = e;
  480. worksheetName = worksheetName.Remove(worksheetName.Length - 1);
  481. }
  482. if (worksheetName.Length <= 0)
  483. throw nameLengthExceed;
  484. } while (nameLengthExceed != null);
  485. ////去掉名称的后缀,不然为sheet页命名会报错
  486. //if (model.picName.LastIndexOf(".") != -1)
  487. // m_worksheet.Name = model.picName.Remove(model.picName.LastIndexOf("."));
  488. //else
  489. // m_worksheet.Name = model.picName;
  490. AddTableToExcelSheet(m_worksheet, 1, 1, model.dataList);
  491. sheetIndex++;
  492. }
  493. m_worksheet.SaveAs(savePath, missing, missing, missing, missing, missing, missing, missing, missing, missing);
  494. m_workbook.Close(false);
  495. m_excel.Application.Quit();
  496. Kill(m_excel);
  497. m_worksheet = null;
  498. m_workbook = null;
  499. m_excel = null;
  500. }
  501. catch (Exception)
  502. {
  503. if (m_excel != null)
  504. {
  505. if (m_workbook != null)
  506. m_workbook.Close(false);
  507. m_excel.Application.Quit();
  508. Kill(m_excel);
  509. }
  510. m_worksheet = null;
  511. m_workbook = null;
  512. m_excel = null;
  513. return false;
  514. }
  515. return true;
  516. }
  517. else
  518. return false;
  519. }
  520. /// <summary>
  521. /// 向excel的sheet页指定单元格插入文本
  522. /// </summary>
  523. /// <param name="worksheet">sheet页</param>
  524. /// <param name="x">插入初始位置横坐标</param>
  525. /// <param name="y">插入初始位置纵坐标</param>
  526. /// <param name="content">文本内容</param>
  527. public static void AddContentToExcelSheet(MSExcel.Worksheet worksheet, int x, int y, string content)
  528. {
  529. worksheet.Cells[x, y] = content;
  530. }
  531. /// <summary>
  532. /// 向excel的sheet页指定单元格插入表格(自行拼接的list形式)
  533. /// </summary>
  534. /// <param name="worksheet">sheet页</param>
  535. /// <param name="x">插入初始位置横坐标</param>
  536. /// <param name="y">插入初始位置纵坐标</param>
  537. /// <param name="contentList">表格对象</param>
  538. public static void AddTableToExcelSheet(MSExcel.Worksheet worksheet, int x, int y, List<List<string>> contentList)
  539. {
  540. if(contentList.Count > 0)
  541. {
  542. for (int i = x; i < contentList.Count + 1; i++)
  543. {
  544. List<string> rowContent = contentList[i - 1];
  545. if(rowContent.Count > 0)
  546. {
  547. for(int j = y; j < rowContent.Count + 1; j++)
  548. {
  549. worksheet.Cells[i, j] = rowContent[j - 1];
  550. }
  551. }
  552. }
  553. }
  554. }
  555. public static void AddExportCalipersSheet(MSExcel.Worksheet worksheet, System.Data.DataTable calipersTable)
  556. {
  557. if (calipersTable.Rows.Count > 0)
  558. {
  559. for (int i = 0; i < calipersTable.Columns.Count; i++)
  560. {
  561. worksheet.Cells[1, i + 1] = calipersTable.Columns[i].ColumnName;
  562. }
  563. for (int j = 0; j < calipersTable.Rows.Count; j++)
  564. {
  565. for (int k = 0; k < calipersTable.Columns.Count; k++)
  566. {
  567. worksheet.Cells[j + 2, k + 1] = calipersTable.Rows[j][k].ToString();
  568. }
  569. }
  570. }
  571. }
  572. /// <summary>
  573. /// 获取excel文档指定位置的内容
  574. /// </summary>
  575. /// <param name="savePath"></param>
  576. /// <param name="tagPositionDic"></param>
  577. /// <returns></returns>
  578. public static Dictionary<string, string> GetContentFromExcel(string savePath, Dictionary<string, string> tagPositionDic)
  579. {
  580. if (!File.Exists(savePath) || tagPositionDic==null)
  581. return null;
  582. else
  583. {
  584. try
  585. {
  586. Dictionary<string, string> tagValueDic = new Dictionary<string, string>();
  587. m_excel = new MSExcel.Application();
  588. m_workbook = m_excel.Workbooks.Add(savePath);
  589. m_worksheet = m_workbook.Sheets.Item[1];//公式固定在第一个sheet页
  590. foreach(KeyValuePair<string, string> kvp in tagPositionDic)
  591. {
  592. string cellContent = m_worksheet.Range[kvp.Value].Value[MSExcel.XlRangeValueDataType.xlRangeValueDefault] == null ? ""
  593. : Convert.ToString(m_worksheet.Range[kvp.Value].Value[MSExcel.XlRangeValueDataType.xlRangeValueDefault]);
  594. tagValueDic.Add(kvp.Key, cellContent);
  595. }
  596. m_workbook.Close(false);
  597. m_excel.Application.Quit();
  598. Kill(m_excel);
  599. m_worksheet = null;
  600. m_workbook = null;
  601. m_excel = null;
  602. return tagValueDic;
  603. }
  604. catch(Exception)
  605. {
  606. if (m_excel != null)
  607. {
  608. if (m_workbook != null)
  609. m_workbook.Close(false);
  610. m_excel.Application.Quit();
  611. Kill(m_excel);
  612. }
  613. m_worksheet = null;
  614. m_workbook = null;
  615. m_excel = null;
  616. return null;
  617. }
  618. }
  619. }
  620. /// <summary>
  621. /// 通过模板创建word报告文档
  622. /// </summary>
  623. /// <param name="analyzeSettingModel"></param>
  624. /// <param name="tagValueDic"></param>
  625. /// <param name="bitmapList"></param>
  626. public static void CreateNewWordWithContent(AutoAnalyzeSettingModel analyzeSettingModel, Dictionary<string, string> tagValueDic, List<Bitmap> bitmapList, double pointPitch, double unitLength, decimal gainMultiple, string lblResult)
  627. {
  628. if(File.Exists(analyzeSettingModel.modulePath) && Directory.Exists(analyzeSettingModel.savePath))
  629. {
  630. string newFilePath = analyzeSettingModel.savePath + "\\" + analyzeSettingModel.analyzeClassify +// "报告" +
  631. DateTime.Now.ToString("yyyyMMddHHmmss") + ".docx";
  632. if (newFilePath.IndexOf("\\\\") != -1)
  633. newFilePath = newFilePath.Replace("\\\\", "\\");
  634. try
  635. {
  636. File.Copy(analyzeSettingModel.modulePath, newFilePath, true);
  637. }
  638. catch (Exception)
  639. {
  640. //MessageBox.Show("word模板文件已打开,请关闭后重试");
  641. return;
  642. }
  643. Object pathObj = newFilePath;
  644. try
  645. {
  646. m_word = new MSWord.Application();
  647. m_doc = m_word.Documents.Open(ref pathObj,
  648. ref missing, ref missing, ref missing, ref missing, ref missing,
  649. ref missing, ref missing, ref missing, ref missing, ref missing,
  650. ref missing, ref missing, ref missing, ref missing, ref missing);
  651. foreach (MSWord.Bookmark bk in m_doc.Bookmarks)
  652. {
  653. if (bk.Name == "customerName")
  654. bk.Range.Text = analyzeSettingModel.customerName;
  655. else if (bk.Name == "telephone")
  656. bk.Range.Text = analyzeSettingModel.telephone;
  657. else if (bk.Name == "sampleName")
  658. bk.Range.Text = analyzeSettingModel.sampleName;
  659. else if (bk.Name == "sampleDescription")
  660. bk.Range.Text = analyzeSettingModel.sampleDescription;
  661. else if (bk.Name == "checkItem")
  662. bk.Range.Text = analyzeSettingModel.checkItem;
  663. else if (bk.Name == "methodStandard")
  664. bk.Range.Text = analyzeSettingModel.methodStandard;
  665. else if (bk.Name == "receiveDate")
  666. bk.Range.Text = analyzeSettingModel.receiveDate.ToString("yyyy/MM/dd");
  667. else if (bk.Name == "checkDate")
  668. bk.Range.Text = analyzeSettingModel.checkDate.ToString("yyyy/MM/dd");
  669. else if (bk.Name == "reportDate")
  670. bk.Range.Text = analyzeSettingModel.reportDate.ToString("yyyy/MM/dd");
  671. else if (bk.Name == "reportNumber")
  672. bk.Range.Text = analyzeSettingModel.reportNumber;
  673. else if (bk.Name == "checkRegion")
  674. bk.Range.Text = analyzeSettingModel.checkRegion;
  675. else if (bk.Name == "checkEnvironment")
  676. bk.Range.Text = analyzeSettingModel.checkEnvironment;
  677. else if (bk.Name == "level")
  678. bk.Range.Text = lblResult;
  679. else if (bk.Name == "picture")
  680. {
  681. if (bitmapList != null && bitmapList.Count > 0)
  682. {
  683. bitmapList.Reverse();
  684. for (int i = 0; i < bitmapList.Count; i++)
  685. {
  686. Bitmap bitmap = GetFixedMultipleBitmap(bitmapList[i], pointPitch, unitLength, gainMultiple);
  687. int oldWidth = bitmap.Width;
  688. int oldHeight = bitmap.Height;
  689. float targetWidth = 0;
  690. float targetHeight = 0;
  691. double pantographRatio = 0;
  692. if (bitmapList[i].Tag != null)
  693. {
  694. pantographRatio = (double)bitmapList[i].Tag;//标尺*放大倍数
  695. }
  696. else
  697. {
  698. pantographRatio = unitLength * (double)gainMultiple;//标尺*放大倍数
  699. }
  700. double aspectRatio = oldWidth / (oldHeight * 1d);//宽高比
  701. if (oldWidth <= oldHeight)
  702. {
  703. // 定倍(A4)计算公式:图片像素(宽) * 当前图片标尺 * 当前图片放大倍数
  704. targetWidth = (float)(28.35 * oldWidth * pantographRatio) / 10000; //将单位转换成磅
  705. targetHeight = (float)(targetWidth / aspectRatio);
  706. }
  707. else
  708. {
  709. // 定倍(A4)计算公式:图片像素(高) * 当前图片标尺 * 当前图片放大倍数
  710. targetHeight = (float)(28.35 * oldHeight * pantographRatio) / 10000;//将单位转换成磅
  711. targetWidth = (float)(targetHeight * aspectRatio);
  712. }
  713. try
  714. {
  715. //缩放的Bitmap尺寸
  716. int new_w = (int)bitmap.Width / 4;
  717. int new_h = (int)bitmap.Height / 4;
  718. Bitmap b = new Bitmap(new_w,new_h);
  719. Graphics g = Graphics.FromImage(b);
  720. g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
  721. g.DrawImage(bitmap,new System.Drawing.Rectangle(0,0,new_w,new_h),new System.Drawing.Rectangle(0,0,bitmap.Width,bitmap.Height),GraphicsUnit.Pixel);
  722. //通过粘贴板的方式可以不使用本地图片
  723. Clipboard.SetDataObject(b);
  724. bk.Range.Paste();
  725. b.Dispose();
  726. g.Dispose();
  727. }
  728. catch(Exception e)
  729. {
  730. string m = e.Message;
  731. }
  732. //控制插入word图片大小
  733. m_doc.InlineShapes[1].Width = targetWidth;
  734. m_doc.InlineShapes[1].Height = targetHeight;
  735. }
  736. }
  737. }
  738. else
  739. {
  740. if (tagValueDic != null && tagValueDic.Count > 0)
  741. {
  742. foreach (KeyValuePair<string, string> kvp in tagValueDic)
  743. {
  744. if (bk.Name == kvp.Key)
  745. {
  746. bk.Range.Text = kvp.Value;
  747. break;
  748. }
  749. }
  750. }
  751. }
  752. }
  753. m_doc.Save();
  754. m_doc.Close(true);
  755. m_word.Quit();
  756. }
  757. catch(Exception)
  758. {
  759. if(m_word != null)
  760. {
  761. if(m_doc != null)
  762. m_doc.Close(false);
  763. m_word.Quit();
  764. }
  765. }
  766. m_doc = null;
  767. m_word = null;
  768. }
  769. }
  770. /// <summary>
  771. /// 导出项目使用,与生成报告区别的是存储路径与命名
  772. /// </summary>
  773. /// <param name="analyzeSettingModel"></param>
  774. /// <param name="tagValueDic"></param>
  775. /// <param name="bitmapList"></param>
  776. /// <param name="newPath"></param>
  777. /// <param name="newCode"></param>
  778. public static void CreateNewWordWithContent(AnalyzeSettingModel analyzeSettingModel, Dictionary<string, string> tagValueDic, List<Bitmap> bitmapList,
  779. string newPath, string newCode)
  780. {
  781. if (File.Exists(analyzeSettingModel.modulePath) && Directory.Exists(newPath))
  782. {
  783. string newFilePath = newPath + "\\" + newCode + ".docx";
  784. if (newFilePath.IndexOf("\\\\") != -1)
  785. newFilePath = newFilePath.Replace("\\\\", "\\");
  786. try
  787. {
  788. File.Copy(analyzeSettingModel.modulePath, newFilePath, true);
  789. }
  790. catch (Exception)
  791. {
  792. return;
  793. }
  794. Object pathObj = newFilePath;
  795. try
  796. {
  797. m_word = new MSWord.Application();
  798. m_doc = m_word.Documents.Open(ref pathObj,
  799. ref missing, ref missing, ref missing, ref missing, ref missing,
  800. ref missing, ref missing, ref missing, ref missing, ref missing,
  801. ref missing, ref missing, ref missing, ref missing, ref missing);
  802. foreach (MSWord.Bookmark bk in m_doc.Bookmarks)
  803. {
  804. if (bk.Name == "itemNumber")
  805. bk.Range.Text = analyzeSettingModel.itemNumber;
  806. else if (bk.Name == "ratingDate")
  807. bk.Range.Text = analyzeSettingModel.ratingDate.ToString("yyyy/MM/dd");
  808. else if (bk.Name == "inspectionPerson")
  809. bk.Range.Text = analyzeSettingModel.inspectionPerson;
  810. else if (bk.Name == "contact")
  811. bk.Range.Text = analyzeSettingModel.contact;
  812. else if (bk.Name == "inspectionDepartment")
  813. bk.Range.Text = analyzeSettingModel.inspectionDepartment;
  814. else if (bk.Name == "inspectionDate")
  815. bk.Range.Text = analyzeSettingModel.inspectionDate.ToString("yyyy/MM/dd");
  816. else if (bk.Name == "other")
  817. {
  818. if (analyzeSettingModel.otherList != null && analyzeSettingModel.otherList.Count > 0)
  819. {
  820. MSWord.Table m_table = m_doc.Tables.Add(bk.Range, analyzeSettingModel.otherList.Count + 1, 2, ref missing, ref missing);
  821. m_table.Borders.OutsideLineStyle = MSWord.WdLineStyle.wdLineStyleThickThinLargeGap;
  822. m_table.Borders.InsideLineStyle = MSWord.WdLineStyle.wdLineStyleSingle;
  823. m_table.Cell(1, 1).Range.Text = "名称";
  824. m_table.Cell(1, 2).Range.Text = "内容";
  825. for (int i = 0; i < analyzeSettingModel.otherList.Count; i++)
  826. {
  827. m_table.Cell(2 + i, 1).Range.Text = analyzeSettingModel.otherList[i].name;
  828. m_table.Cell(2 + i, 2).Range.Text = analyzeSettingModel.otherList[i].content;
  829. }
  830. }
  831. }
  832. else if (bk.Name == "picture")
  833. {
  834. if (bitmapList != null && bitmapList.Count > 0)
  835. {
  836. bitmapList.Reverse();
  837. for (int i = 0; i < bitmapList.Count; i++)
  838. {
  839. double pointPitch = 0;
  840. double unitLength = 0;
  841. decimal gainMultiple = 0;
  842. Bitmap bitmap = GetFixedMultipleBitmap(bitmapList[i], pointPitch, unitLength, gainMultiple);
  843. int oldWidth = bitmap.Width;
  844. int oldHeight = bitmap.Height;
  845. float targetWidth = 0;
  846. float targetHeight = 0;
  847. double pantographRatio = 0;
  848. if (bitmapList[i].Tag != null)
  849. {
  850. pantographRatio = (double)bitmapList[i].Tag;//标尺*放大倍数
  851. }
  852. else
  853. {
  854. pantographRatio = unitLength * (double)gainMultiple;//标尺*放大倍数
  855. }
  856. double aspectRatio = oldWidth / (oldHeight * 1d);//宽高比
  857. if (oldWidth <= oldHeight)
  858. {
  859. // 定倍(A4)计算公式:图片像素(宽) * 当前图片标尺 * 当前图片放大倍数
  860. targetWidth = (float)(28.35 * oldWidth * pantographRatio) / 10000; //将单位转换成磅
  861. targetHeight = (float)(targetWidth / aspectRatio);
  862. }
  863. else
  864. {
  865. // 定倍(A4)计算公式:图片像素(高) * 当前图片标尺 * 当前图片放大倍数
  866. targetHeight = (float)(28.35 * oldHeight * pantographRatio) / 10000;//将单位转换成磅
  867. targetWidth = (float)(targetHeight * aspectRatio);
  868. }
  869. //通过粘贴板的方式可以不使用本地图片
  870. Clipboard.SetDataObject(bitmap);
  871. bk.Range.Paste();
  872. //控制插入word图片大小
  873. m_doc.InlineShapes[1].Width = targetWidth;
  874. m_doc.InlineShapes[1].Height = targetHeight;
  875. ////通过粘贴板的方式可以补使用本地图片
  876. //Clipboard.SetDataObject(bitmapList[i]);
  877. //bk.Range.Paste();
  878. ////需要本地图片,暂时不可用
  879. ////bk.Range.InlineShapes.AddPicture(bitmapList[i].ToString(), ref missing, ref missing, ref missing);
  880. }
  881. }
  882. }
  883. else
  884. {
  885. if (tagValueDic != null && tagValueDic.Count > 0)
  886. {
  887. foreach (KeyValuePair<string, string> kvp in tagValueDic)
  888. {
  889. if (bk.Name == kvp.Key)
  890. {
  891. bk.Range.Text = kvp.Value;
  892. break;
  893. }
  894. }
  895. }
  896. }
  897. }
  898. m_doc.Save();
  899. m_doc.Close(true);
  900. m_word.Quit();
  901. }
  902. catch (Exception)
  903. {
  904. if (m_word != null)
  905. {
  906. if (m_doc != null)
  907. m_doc.Close(false);
  908. m_word.Quit();
  909. }
  910. }
  911. m_doc = null;
  912. m_word = null;
  913. }
  914. }
  915. /// <summary>
  916. /// 杀死进程
  917. /// </summary>
  918. /// <param name="hwnd"></param>
  919. /// <param name="ID"></param>
  920. /// <returns></returns>
  921. [DllImport("User32.dll", CharSet = CharSet.Auto)]
  922. public static extern int GetWindowThreadProcessId(IntPtr hwnd, out int ID);
  923. public static void Kill(MSExcel.Application excel)
  924. {
  925. IntPtr t = new IntPtr(excel.Hwnd); //得到这个句柄,具体作用是得到这块内存入口
  926. int k = 0;
  927. GetWindowThreadProcessId(t, out k); //得到本进程唯一标志k
  928. System.Diagnostics.Process p = System.Diagnostics.Process.GetProcessById(k); //得到对进程k的引用
  929. p.Kill(); //关闭进程k
  930. }
  931. /// <summary>
  932. /// excel英文位置转坐标-以后可能用到
  933. /// 如A1转为(1,1);
  934. /// </summary>
  935. /// <param name="columnName"></param>
  936. /// <returns></returns>
  937. public static System.Drawing.Point ExcelRangeToCell(string cell_positon)
  938. {
  939. string positionX = Regex.Replace(cell_positon, "[0-9]", "", RegexOptions.IgnoreCase);
  940. string positionY = Regex.Replace(cell_positon, "[A-Z]", "", RegexOptions.IgnoreCase);
  941. if (!Regex.IsMatch(positionX.ToUpper(), @"[A-Z]+"))
  942. return new System.Drawing.Point(0, 0);
  943. int index = 0;
  944. char[] chars = positionX.ToUpper().ToCharArray();
  945. for (int i = 0; i < chars.Length; i++)
  946. {
  947. index += ((int)chars[i] - (int)'A' + 1) * (int)Math.Pow(26, chars.Length - i - 1);
  948. }
  949. return new System.Drawing.Point(index, Convert.ToInt32(positionY));
  950. }
  951. /// <summary>
  952. /// 保存数据到execl
  953. /// </summary>
  954. /// <param name="excelModulePath">excel公式模板路径</param>
  955. /// <param name="saveAsPath">新文件另存路径</param>
  956. /// <param name="sheets">数据对象模型</param>
  957. /// <returns></returns>
  958. public static bool SaveDataToExcel(object Template, string saveAsPath, List<List<List<string>>> sheets)
  959. {
  960. try
  961. {
  962. m_excel = new MSExcel.Application();
  963. m_workbook = m_excel.Workbooks.Add(Template);
  964. for (int i = 0; i < sheets.Count; i++)
  965. {
  966. List<List<string>> data = sheets[i];
  967. if (m_workbook.Sheets.Count <= i)
  968. {
  969. m_workbook.Worksheets.Add(After: m_workbook.Sheets.get_Item(m_workbook.Sheets.Count));
  970. }
  971. m_worksheet = m_workbook.Sheets.Item[i + 1];
  972. AddTableToExcelSheet(m_worksheet, 1, 1, data);
  973. }
  974. m_workbook.SaveAs(saveAsPath, missing, missing, missing, missing, missing, MSExcel.XlSaveAsAccessMode.xlExclusive, missing, missing, missing);
  975. }
  976. catch (Exception e)
  977. {
  978. throw e;
  979. }
  980. finally
  981. {
  982. if (m_excel != null)
  983. {
  984. if (m_workbook != null)
  985. m_workbook.Close(false);
  986. m_excel.Application.Quit();
  987. Kill(m_excel);
  988. }
  989. m_worksheet = null;
  990. m_workbook = null;
  991. m_excel = null;
  992. }
  993. return true;
  994. }
  995. /// <summary>
  996. /// 保存数据到execl
  997. /// </summary>
  998. /// <param name="excelModulePath">excel公式模板路径</param>
  999. /// <param name="saveAsPath">新文件另存路径</param>
  1000. /// <param name="sheets">数据对象模型</param>
  1001. /// <returns></returns>
  1002. public static bool SaveDataToExcel(string saveAsPath, List<List<List<string>>> sheets)
  1003. {
  1004. return SaveDataToExcel(MSExcel.XlWBATemplate.xlWBATWorksheet,saveAsPath,sheets);
  1005. }
  1006. /// <summary>
  1007. /// 导出结果(一个sheet页)
  1008. /// </summary>
  1009. public static void ExportDataToExcel(string path, List<System.Data.DataTable> datas, bool multiSheet=false)
  1010. {
  1011. Worksheet workSheet = null;
  1012. Workbook workBook = null;
  1013. Workbooks workbooks = null;
  1014. MSExcel.Application xlApp = null;
  1015. try
  1016. {
  1017. xlApp = new MSExcel.Application();
  1018. workbooks = xlApp.Workbooks;
  1019. workBook = workbooks.Add(XlWBATemplate.xlWBATWorksheet);
  1020. if (multiSheet)
  1021. {
  1022. if (datas != null && datas.Count > 0)
  1023. {
  1024. int ka = 1;
  1025. foreach (System.Data.DataTable dtb in datas)
  1026. {
  1027. if (ka > 1)
  1028. {
  1029. Sheets sheets = workBook.Worksheets;
  1030. workSheet = (Worksheet)sheets.Add(Missing.Value, Missing.Value, Missing.Value, Missing.Value);
  1031. }
  1032. else
  1033. {
  1034. workSheet = (Worksheet)workBook.Worksheets[1];
  1035. }
  1036. ka++;
  1037. workSheet.Cells.NumberFormat = "@";
  1038. for (int i = 0; i < dtb.Columns.Count; i++)
  1039. {
  1040. workSheet.Cells[1, i + 1] = dtb.Columns[i].ColumnName;
  1041. }
  1042. for (int j = 0; j < dtb.Rows.Count; j++)
  1043. {
  1044. for (int k = 0; k < dtb.Columns.Count; k++)
  1045. {
  1046. workSheet.Cells[j+2, k+1] = dtb.Rows[j][k].ToString();
  1047. }
  1048. }
  1049. }
  1050. }
  1051. }
  1052. else
  1053. {
  1054. workBook = workbooks.Add(XlWBATemplate.xlWBATWorksheet);
  1055. workSheet = (Worksheet)workBook.Worksheets[1];
  1056. if (datas != null && datas.Count > 0)
  1057. {
  1058. int kk = 0;
  1059. int jj = 0;
  1060. foreach (System.Data.DataTable dtb in datas)
  1061. {
  1062. if (kk == 0)
  1063. {
  1064. for (int i = 0; i < dtb.Columns.Count; i++)
  1065. {
  1066. workSheet.Cells[1, i + 1] = dtb.Columns[i].ColumnName;
  1067. }
  1068. kk++;
  1069. }
  1070. for (int j = 0; j < dtb.Rows.Count; j++)
  1071. {
  1072. for (int k = 0; k < dtb.Columns.Count; k++)
  1073. {
  1074. workSheet.Cells[jj + 2, k + 1] = dtb.Rows[j][k].ToString();
  1075. }
  1076. jj++;
  1077. }
  1078. }
  1079. }
  1080. }
  1081. object nothing = Type.Missing;
  1082. workBook.SaveAs(path, nothing, nothing, nothing, nothing, nothing,
  1083. MSExcel.XlSaveAsAccessMode.xlExclusive, nothing, nothing, nothing, nothing, nothing);
  1084. }
  1085. catch (Exception)
  1086. {
  1087. }
  1088. finally
  1089. {
  1090. if (xlApp != null)
  1091. {
  1092. if (xlApp != null && workBook!=null)
  1093. workBook.Close(false);
  1094. xlApp.Quit();
  1095. Kill(xlApp);
  1096. }
  1097. }
  1098. }
  1099. /// <summary>
  1100. /// 保存图片到本地
  1101. /// </summary>
  1102. /// <param name="bitList"></param>
  1103. public static void SaveAllImage(List<Bitmap> bitList, string newPath, string newCode)
  1104. {
  1105. if(bitList != null && bitList.Count > 0)
  1106. {
  1107. int originNum = 0;
  1108. int codeNum = 0;
  1109. for (int i = 0; i < bitList.Count; i++)
  1110. {
  1111. string bitPath = "";
  1112. //分别为原图和处理后的图命名
  1113. if(i % 2 == 0)
  1114. {
  1115. originNum++;
  1116. bitPath = newPath + "//origin-" + originNum + ".jpg";
  1117. }
  1118. else
  1119. {
  1120. codeNum++;
  1121. bitPath = newPath + "/" + newCode + "-" + codeNum + ".jpg";
  1122. }
  1123. bitList[i].Save(bitPath);
  1124. }
  1125. }
  1126. }
  1127. /// <summary>
  1128. /// xls转xlsx 但是需要office激活,没测试
  1129. /// </summary>
  1130. /// <param name="path"></param>
  1131. /// <param name="name"></param>
  1132. public static bool ConvertWorkbook(string path, string name)
  1133. {
  1134. bool action = false;
  1135. var app = new Microsoft.Office.Interop.Excel.Application { Visible = false };
  1136. Workbook book = null;
  1137. try
  1138. {
  1139. book = app.Workbooks.Open(path);
  1140. }
  1141. catch (Exception)
  1142. {
  1143. }
  1144. if(book!=null)
  1145. {
  1146. //注意,新的文件名没后缀
  1147. book.SaveAs(Filename: Path.GetDirectoryName(path) + "\\" + name, FileFormat: Microsoft.Office.Interop.Excel.XlFileFormat.xlOpenXMLWorkbook);
  1148. book.Close();
  1149. action = true;
  1150. }
  1151. app.Quit();
  1152. Kill(app);
  1153. return action;
  1154. }
  1155. public static bool aaaaa()
  1156. {
  1157. try
  1158. {
  1159. m_excel = new MSExcel.Application();
  1160. m_workbook = m_excel.Workbooks.Open("C:\\Users\\zyh\\Desktop\\111.xlsx");
  1161. m_worksheet = m_workbook.Sheets.Item[2];//数据固定插入在第二个sheet页
  1162. MSExcel.Worksheet m_worksheet1 = m_workbook.Sheets.Item[1];//数据固定插入在第二个sheet页
  1163. Microsoft.Office.Interop.Excel.Pictures pics = (Microsoft.Office.Interop.Excel.Pictures)m_worksheet1.Pictures(Type.Missing);
  1164. for (int i = 1; i <= pics.Count; i++)
  1165. {
  1166. //可以循环这个excel里面的图
  1167. Picture pic = pics.Item(i) as Picture;
  1168. //可以获取图的左上cell
  1169. Range topleft = pic.TopLeftCell;
  1170. //可以获取图的右下cell
  1171. Range rightbottom = pic.BottomRightCell;
  1172. /*Microsoft.Office.Interop.Excel.Range rng = m_worksheet.get_Range(topleft, rightbottom);
  1173. pics.Left = (double)pic.Left;
  1174. pics.Top = (double)pic.Top;
  1175. pics.Width = (double)pic.Width;
  1176. pics.Height = (double)pic.Height;*/
  1177. pics.Select(pic).Insert("C:\\Users\\zyh\\Desktop\\d\\imgbox1.jpg", Type.Missing);
  1178. }
  1179. m_worksheet.SaveAs("C:\\Users\\zyh\\Desktop\\111.xlsx", missing, missing, missing, missing, missing, missing, missing, missing, missing);
  1180. m_workbook.Close(false);
  1181. m_excel.Application.Quit();
  1182. Kill(m_excel);
  1183. m_worksheet = null;
  1184. m_workbook = null;
  1185. m_excel = null;
  1186. }
  1187. catch (Exception ex)
  1188. {
  1189. if (m_excel != null)
  1190. {
  1191. if (m_workbook != null)
  1192. m_workbook.Close(false);
  1193. m_excel.Application.Quit();
  1194. Kill(m_excel);
  1195. }
  1196. m_worksheet = null;
  1197. m_workbook = null;
  1198. m_excel = null;
  1199. return false;
  1200. }
  1201. return true;
  1202. /*m_excel = new MSExcel.Application();
  1203. m_excel.Workbooks.Open("C:\\Users\\zyh\\Desktop\\111.xlsx");
  1204. m_worksheet = m_excel.Sheets.Item[1];
  1205. Microsoft.Office.Interop.Excel.Pictures pics = (Microsoft.Office.Interop.Excel.Pictures)m_worksheet.Pictures(Type.Missing);
  1206. for (int i=1; i<= pics.Count; i++)
  1207. {
  1208. //可以循环这个excel里面的图
  1209. Picture pic = pics.Item(i) as Picture;
  1210. //可以获取图的左上cell
  1211. Range topleft = pic.TopLeftCell;
  1212. //可以获取图的右下cell
  1213. Range rightbottom = pic.BottomRightCell;
  1214. Microsoft.Office.Interop.Excel.Range rng = m_worksheet.get_Range("A1", "B2");
  1215. try
  1216. {
  1217. pics.Insert("C:/Users/zyh/Desktop/imgbox1.jpg", Type.Missing);
  1218. pics.Left = (double)rng.Left;
  1219. pics.Top = (double)rng.Top;
  1220. pics.Width = (double)rng.Width;
  1221. pics.Height = (double)rng.Height;
  1222. }
  1223. catch(Exception ex)
  1224. {
  1225. }
  1226. }
  1227. m_worksheet.SaveAs("C:/Users/zyh/Desktop/333.xlsx", missing, missing, missing, missing, missing, missing, missing, missing, missing);
  1228. m_workbook.Close(false);
  1229. m_excel.Application.Quit();
  1230. Kill(m_excel);
  1231. m_worksheet = null;
  1232. m_workbook = null;
  1233. m_excel = null;*/
  1234. }
  1235. }
  1236. }