ExcelHelper.cs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Data;
  6. using System.Reflection;
  7. using System.IO;
  8. using System.Diagnostics;
  9. using System.Collections;
  10. using System.Runtime.InteropServices;
  11. using Microsoft.Office.Interop.Excel;
  12. using Infragistics.Win.UltraWinGrid;
  13. using System.Windows.Forms;
  14. namespace Core.StlMes.Client.Plan.Order
  15. {
  16. /**/
  17. /// <summary>
  18. /// 功能说明: 为套用模板输出Excel定制,并对数据进行分页
  19. /// </summary>
  20. public class ExcelHelper
  21. {
  22. protected string templetFile = null;
  23. protected string outputFile = null;
  24. protected object missing = Missing.Value;
  25. /// <summary>
  26. /// 构造函数,需指定模板文件和输出文件完整路径
  27. /// </summary>
  28. /// <param name="templetFilePath"> Excel模板文件路径 </param>
  29. /// <param name="outputFilePath"> 输出Excel文件路径 </param>
  30. public ExcelHelper(string templetFilePath, string outputFilePath)
  31. {
  32. if (templetFilePath == null)
  33. throw new Exception(" Excel模板文件路径不能为空! ");
  34. if (!File.Exists(templetFilePath))
  35. throw new Exception(" 指定路径的Excel模板文件不存在! ");
  36. this.templetFile = templetFilePath;
  37. this.outputFile = outputFilePath;
  38. if (CheckPath() == false)
  39. throw new Exception(" 输出Excel文件路径不能为空! ");
  40. }
  41. /// <summary>
  42. /// 获取Cells单元格的值
  43. /// </summary>
  44. /// <param name="x">第x行,Excel的起始列为1</param>
  45. /// <param name="y">第y列,Excel的起始行为1</param>
  46. /// <returns>object</returns>
  47. public string GetCell_Value(int x, int y,Microsoft.Office.Interop.Excel.Worksheet sheet)
  48. {
  49. if (sheet == null) { return ""; }
  50. object[] Parameters_Cells = new object[2] { x, y }; //第x行,第y列
  51. object m_objCells = sheet.GetType().InvokeMember("Cells", BindingFlags.GetProperty | BindingFlags.OptionalParamBinding, null, sheet, Parameters_Cells);
  52. if (m_objCells == null)
  53. {
  54. return "";
  55. }
  56. object m_objCellsValue = sheet.GetType().InvokeMember("Value", BindingFlags.GetProperty, null, m_objCells, new object[0]);
  57. if (m_objCellsValue == null)
  58. {
  59. return "";
  60. }
  61. System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objCells);
  62. GC.GetTotalMemory(true);
  63. return m_objCellsValue.ToString();
  64. }
  65. /// <summary>
  66. /// 获取WorkSheet数量
  67. /// </summary>
  68. /// <param name="rowCount"> 记录总行数 </param>
  69. /// <param name="rows"> 每WorkSheet行数 </param>
  70. private int GetSheetCount(int rowCount, int rows)
  71. {
  72. int n = rowCount % rows; // 余数
  73. if (n == 0)
  74. return rowCount / rows;
  75. else
  76. return Convert.ToInt32(rowCount / rows) + 1;
  77. }
  78. /// <summary>
  79. /// 将二维数组数据写入Excel文件(套用模板并分页)
  80. /// </summary>
  81. /// <param name="arr"> 二维数组 </param>
  82. /// <param name="rows"> 每个WorkSheet写入多少行数据 </param>
  83. /// <param name="top"> 行索引-从1开始 </param>
  84. /// <param name="left"> 列索引-从1开始 </param>
  85. /// <param name="sheetPrefixName"> WorkSheet前缀名,比如:前缀名为“Sheet”,那么WorkSheet名称依次为“Sheet-1,Sheet-2” </param>
  86. public bool ArrayToExcel(object[,] arr, int rows, int top, int left, string sheetPrefixName)
  87. {
  88. int rowCount = arr.GetLength(0); // 二维数组行数(一维长度)
  89. int colCount = arr.GetLength(1); // 二维数据列数(二维长度)
  90. int sheetCount = this.GetSheetCount(rowCount, rows); // WorkSheet个数
  91. if (sheetPrefixName == null || sheetPrefixName.Trim() == "")
  92. sheetPrefixName = " Sheet ";
  93. // 创建一个Application对象并使其可见
  94. Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
  95. app.Visible = false;
  96. try
  97. {
  98. // 打开模板文件,得到WorkBook对象
  99. Microsoft.Office.Interop.Excel.Workbook workBook = app.Workbooks._Open(templetFile, missing, missing, missing, missing, missing,
  100. missing, missing, missing, missing, missing, missing, missing);
  101. // 得到WorkSheet对象
  102. Microsoft.Office.Interop.Excel.Worksheet workSheet = (Microsoft.Office.Interop.Excel.Worksheet)workBook.Sheets.get_Item(1);
  103. // 复制sheetCount-1个WorkSheet对象
  104. for (int i = 1; i < sheetCount; i++)
  105. {
  106. ((Microsoft.Office.Interop.Excel.Worksheet)workBook.Worksheets.get_Item(i)).Copy(missing, workBook.Worksheets[i]);
  107. }
  108. #region 将二维数组数据写入Excel
  109. //将二维数组数据写入Excel
  110. for (int i = 1; i <= sheetCount; i++)
  111. {
  112. int startRow = (i - 1) * rows; // 记录起始行索引
  113. int endRow = i * rows; // 记录结束行索引
  114. // 若是最后一个WorkSheet,那么记录结束行索引为源DataTable行数
  115. if (i == sheetCount)
  116. endRow = rowCount;
  117. // 获取要写入数据的WorkSheet对象,并重命名
  118. Microsoft.Office.Interop.Excel.Worksheet sheet = (Microsoft.Office.Interop.Excel.Worksheet)workBook.Worksheets.get_Item(i);
  119. sheet.Name = sheetPrefixName + " - " + i.ToString();
  120. //设定输出部分的样式
  121. Microsoft.Office.Interop.Excel.Range excelRange = sheet.get_Range(SeqToXlsCol[left] + (top + startRow - (i - 1) * rows),
  122. SeqToXlsCol[left + colCount - 1] + (top + endRow - 1 - (i - 1) * rows));
  123. //excelRange.NumberFormatLocal = "@";
  124. excelRange.Borders.LineStyle = 1;
  125. excelRange.Font.Size = 9;
  126. excelRange.Font.Name = "Arial";
  127. List<ValuesPoint> param = new List<ValuesPoint>();
  128. for (int row = 0; row < rowCount; row++)
  129. {
  130. for (int col = 0; col < colCount; col++)
  131. {
  132. if (arr[row, col].ToString().Length > 500)
  133. {
  134. ValuesPoint value = new ValuesPoint();
  135. value.Values = arr[row, col];
  136. value.Row = row;
  137. value.Col = col;
  138. arr[row, col] = "";
  139. param.Add(value);
  140. }
  141. }
  142. }
  143. //string _BeginPoint = SeqToXlsCol[left] + (top + startRow - (i - 1) * rows);
  144. //string _EndPoint = SeqToXlsCol[left + colCount - 1] + (top + endRow - 1 - (i - 1) * rows);
  145. //SetRangeArray_Value(app, sheet, _BeginPoint, _EndPoint, arr);
  146. //设定header 居中粗体
  147. //sheet.get_Range(IFCF.SeqToXlsCol[left] + top + ":" + IFCF.SeqToXlsCol[left + colCount - 1] + top).Font.Bold = true;
  148. //sheet.get_Range(IFCF.SeqToXlsCol[left] + top + ":" + IFCF.SeqToXlsCol[left + colCount - 1] + top).HorizontalAlignment = XlHAlign.xlHAlignCenter;
  149. // 将二维数组中的数据写入WorkSheet
  150. sheet.get_Range(SeqToXlsCol[left] + (top + startRow - (i - 1) * rows),
  151. SeqToXlsCol[left + colCount - 1] + (top + endRow - 1 - (i - 1) * rows)).Value2 = arr;
  152. for (int cout = 0; cout < param.Count; cout++)
  153. {
  154. int row = param[cout].Row;
  155. int col = param[cout].Col;
  156. sheet.Cells[top + row-startRow, left + col] = param[cout].Values;
  157. }
  158. //for (int j = 0; j < endRow - startRow; j++)
  159. //{
  160. // for (int k = 0; k < colCount; k++)
  161. // {
  162. // sheet.Cells[top + j, left + k] = arr[startRow + j, k];
  163. // }
  164. //}
  165. //自动调整列宽
  166. //sheet.Cells.EntireColumn.AutoFit();
  167. }
  168. #endregion
  169. // 输出Excel文件并退出
  170. //保存Excel的时候,不弹出是否保存的窗口直接进行保存
  171. app.DisplayAlerts = false;
  172. workBook._SaveAs(outputFile, missing, missing, missing, missing, missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, missing, missing, missing, missing);
  173. workBook.Close(null, null, null);
  174. app.Workbooks.Close();
  175. app.Application.Quit();
  176. app.Quit();
  177. System.Runtime.InteropServices.Marshal.ReleaseComObject(workSheet);
  178. System.Runtime.InteropServices.Marshal.ReleaseComObject(workBook);
  179. System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
  180. ExcelProecssKill(app);
  181. workSheet = null;
  182. workBook = null;
  183. app = null;
  184. GC.Collect();
  185. }
  186. catch (Exception ex)
  187. {
  188. ExcelProecssKill(app);
  189. Debug.WriteLine(ex.Message);
  190. MessageBox.Show(ex.Message);
  191. return false;
  192. }
  193. finally
  194. {
  195. ExcelProecssKill(app);
  196. }
  197. return true;
  198. }
  199. /// <summary>
  200. /// 将二维数组数据写入Excel文件(套用模板并分页)
  201. /// </summary>
  202. /// <param name="arr"> 二维数组 </param>
  203. /// <param name="top"> 行索引-从1开始 </param>
  204. /// <param name="left"> 列索引-从1开始 </param>
  205. /// <param name="sheetPrefixName"> WorkSheet前缀名,比如:前缀名为“Sheet”,那么WorkSheet名称依次为“Sheet-1,Sheet-2” </param>
  206. public bool ArrayToExcel(object[,] arr, int top, int left, string sheetPrefixName)
  207. {
  208. int rowCount = arr.GetLength(0); // 二维数组行数(一维长度)
  209. int colCount = arr.GetLength(1); // 二维数据列数(二维长度)
  210. if (sheetPrefixName == null || sheetPrefixName.Trim() == "")
  211. sheetPrefixName = " Sheet ";
  212. // 创建一个Application对象并使其可见
  213. Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
  214. app.Visible = false;
  215. try
  216. {
  217. // 打开模板文件,得到WorkBook对象
  218. Microsoft.Office.Interop.Excel.Workbook workBook = app.Workbooks._Open(templetFile, missing, missing, missing, missing, missing,
  219. missing, missing, missing, missing, missing, missing, missing);
  220. // 得到WorkSheet对象
  221. Microsoft.Office.Interop.Excel.Worksheet workSheet = (Microsoft.Office.Interop.Excel.Worksheet)workBook.Sheets.get_Item(1);
  222. #region 将二维数组数据写入Excel
  223. //将二维数组数据写入Excel
  224. //for (int i = 1; i <= sheetCount; i++)
  225. //{
  226. //int startRow = (i - 1) * rows; // 记录起始行索引
  227. //int endRow = i * rows; // 记录结束行索引
  228. //// 若是最后一个WorkSheet,那么记录结束行索引为源DataTable行数
  229. //if (i == sheetCount)
  230. // endRow = rowCount;
  231. // 获取要写入数据的WorkSheet对象,并重命名
  232. Microsoft.Office.Interop.Excel.Worksheet sheet = (Microsoft.Office.Interop.Excel.Worksheet)workBook.Worksheets.get_Item(1);
  233. sheet.Name = sheetPrefixName + " - 1";
  234. //设定输出部分的样式
  235. Microsoft.Office.Interop.Excel.Range excelRange = sheet.get_Range(SeqToXlsCol[left] + top,
  236. SeqToXlsCol[left + colCount - 1] + (top + rowCount - 1));
  237. //excelRange.NumberFormatLocal = "@";
  238. excelRange.Borders.LineStyle = 1;
  239. excelRange.Font.Size = 9;
  240. excelRange.Font.Name = "Arial";
  241. List<ValuesPoint> param = new List<ValuesPoint>();
  242. for (int row = 0; row < rowCount; row++)
  243. {
  244. for (int col = 0; col < colCount; col++)
  245. {
  246. if (arr[row, col].ToString().Length > 500)
  247. {
  248. ValuesPoint value = new ValuesPoint();
  249. value.Values = arr[row, col];
  250. value.Row = row;
  251. value.Col = col;
  252. arr[row, col] = "";
  253. param.Add(value);
  254. }
  255. }
  256. }
  257. //string _BeginPoint = SeqToXlsCol[left] + (top + startRow - (i - 1) * rows);
  258. //string _EndPoint = SeqToXlsCol[left + colCount - 1] + (top + endRow - 1 - (i - 1) * rows);
  259. //SetRangeArray_Value(app, sheet, _BeginPoint, _EndPoint, arr);
  260. //设定header 居中粗体
  261. //sheet.get_Range(IFCF.SeqToXlsCol[left] + top + ":" + IFCF.SeqToXlsCol[left + colCount - 1] + top).Font.Bold = true;
  262. //sheet.get_Range(IFCF.SeqToXlsCol[left] + top + ":" + IFCF.SeqToXlsCol[left + colCount - 1] + top).HorizontalAlignment = XlHAlign.xlHAlignCenter;
  263. // 将二维数组中的数据写入WorkSheet
  264. sheet.get_Range(SeqToXlsCol[left] + top,
  265. SeqToXlsCol[left + colCount - 1] + (top + rowCount - 1)).Value2 = arr;
  266. for (int cout = 0; cout < param.Count; cout++)
  267. {
  268. int row = param[cout].Row;
  269. int col = param[cout].Col;
  270. sheet.Cells[top + row, left + col] = param[cout].Values;
  271. }
  272. //for (int j = 0; j < endRow - startRow; j++)
  273. //{
  274. // for (int k = 0; k < colCount; k++)
  275. // {
  276. // sheet.Cells[top + j, left + k] = arr[startRow + j, k];
  277. // }
  278. //}
  279. //自动调整列宽
  280. //sheet.Cells.EntireColumn.AutoFit();
  281. #endregion
  282. // 输出Excel文件并退出
  283. //保存Excel的时候,不弹出是否保存的窗口直接进行保存
  284. app.DisplayAlerts = false;
  285. workBook._SaveAs(outputFile, missing, missing, missing, missing, missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, missing, missing, missing, missing);
  286. workBook.Close(null, null, null);
  287. app.Workbooks.Close();
  288. app.Application.Quit();
  289. app.Quit();
  290. System.Runtime.InteropServices.Marshal.ReleaseComObject(workSheet);
  291. System.Runtime.InteropServices.Marshal.ReleaseComObject(workBook);
  292. System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
  293. ExcelProecssKill(app);
  294. workSheet = null;
  295. workBook = null;
  296. app = null;
  297. GC.Collect();
  298. }
  299. catch (Exception ex)
  300. {
  301. ExcelProecssKill(app);
  302. Debug.WriteLine(ex.Message);
  303. MessageBox.Show(ex.Message);
  304. return false;
  305. }
  306. finally
  307. {
  308. ExcelProecssKill(app);
  309. }
  310. return true;
  311. }
  312. [DllImport("User32.dll", CharSet = CharSet.Auto)]
  313. public static extern int GetWindowThreadProcessId(IntPtr hwnd, out int ID);
  314. /// <summary>
  315. /// 对Excel的进程进行处理
  316. /// </summary>
  317. /// <param name="excel"></param>
  318. public static void ExcelProecssKill(Microsoft.Office.Interop.Excel.Application excel)
  319. {
  320. try
  321. {
  322. if (excel != null)
  323. {
  324. IntPtr t = new IntPtr(excel.Hwnd); //得到这个句柄,具体作用是得到这块内存入口
  325. int k = 0;
  326. GetWindowThreadProcessId(t, out k); //得到本进程唯一标志k
  327. System.Diagnostics.Process p = System.Diagnostics.Process.GetProcessById(k); //得到对进程k的引用
  328. p.Kill(); //关闭进程k
  329. }
  330. }
  331. catch (System.Exception ex)
  332. {
  333. Debug.WriteLine(ex.Message);
  334. }
  335. }
  336. /// <summary>
  337. /// 验证输出文件的路径,如果没有就新
  338. /// </summary>
  339. /// <returns>true or false</returns>
  340. private bool CheckPath()
  341. {
  342. try
  343. {
  344. string tempPath = outputFile.Substring(0, outputFile.LastIndexOf("\\"));
  345. if (Directory.Exists(tempPath) == false)
  346. {
  347. Directory.CreateDirectory(tempPath);
  348. }
  349. if (File.Exists(outputFile) == true)
  350. {
  351. File.Delete(outputFile);
  352. //File.Move(outputFile, outputFile + "_" + DateTime.Now.ToString("yyyyMMddHHmmss"));
  353. }
  354. return true;
  355. }
  356. catch (System.Exception ex)
  357. {
  358. Debug.WriteLine(ex.Message);
  359. return false;
  360. }
  361. }
  362. /// <summary>
  363. /// 读取Grid数据,并按模板格式排列成二维数组
  364. /// </summary>
  365. /// <param name="grid">grid表格</param>
  366. /// <param name="top">模板表头行索引-从1开始</param>
  367. /// <param name="left">模板表头列索引-从1开始</param>
  368. /// <returns>二维数组</returns>
  369. public string[,] setModelArr(UltraGrid grid, int top, int left)
  370. {
  371. int count = 0; //模板表头列数
  372. string[,] arr = null;
  373. DateTime beforeTime;
  374. DateTime afterTime;
  375. // 创建一个Application对象并使其可见
  376. beforeTime = DateTime.Now;
  377. Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application(); //new Excel.ApplicationClass();
  378. app.Visible = true;
  379. afterTime = DateTime.Now;
  380. try
  381. {
  382. // 打开模板文件,得到WorkBook对象
  383. Microsoft.Office.Interop.Excel.Workbook workBook = app.Workbooks._Open(templetFile, missing, missing, missing, missing, missing,
  384. missing, missing, missing, missing, missing, missing, missing);
  385. // 得到WorkSheet对象
  386. Microsoft.Office.Interop.Excel.Worksheet workSheet = (Microsoft.Office.Interop.Excel.Worksheet)workBook.Sheets.get_Item(1);
  387. ArrayList headGourp = new ArrayList();
  388. for (int k = left; k < workSheet.Columns.Count; k++)
  389. {
  390. string head = GetCell_Value(top, k, workSheet);
  391. headGourp.Add(head);
  392. if (head.Equals(""))
  393. {
  394. count = k - left;
  395. break;
  396. }
  397. }
  398. arr = new string[grid.Rows.Count, count];
  399. //读取grid数据到二维数组中
  400. for (int k = left, j = 0; k < count + left; k++, j++)
  401. {
  402. string head = headGourp[j].ToString();
  403. //string head = GetCell_Value(top, k, workSheet);
  404. int rows = 0;
  405. for (int i = 0; i < grid.DisplayLayout.Bands[0].Columns.Count; i++)
  406. {
  407. string gridhead = grid.DisplayLayout.Bands[0].Columns[i].Header.Caption;
  408. if (head.Equals(gridhead))
  409. {
  410. foreach (UltraGridRow uRow in grid.Rows)
  411. {
  412. arr[rows, k - 1] = uRow.Cells[i].Value.ToString();
  413. rows++;
  414. }
  415. break;
  416. }
  417. }
  418. }
  419. app.Workbooks.Close();
  420. app.Application.Quit();
  421. app.Quit();
  422. }
  423. catch (Exception ex)
  424. {
  425. ExcelProecssKill(app);
  426. Debug.WriteLine(ex.Message);
  427. return arr;
  428. }
  429. finally
  430. {
  431. ExcelProecssKill(app);
  432. }
  433. return arr;
  434. }
  435. /// <summary>
  436. /// 读取DataTable数据,并按模板格式排列成二维数组
  437. /// </summary>
  438. /// <param name="grid">DataTable</param>
  439. /// <param name="top">模板表头行索引-从1开始</param>
  440. /// <param name="left">模板表头列索引-从1开始</param>
  441. /// <returns>二维数组</returns>
  442. public string[,] setModelArr(System.Data.DataTable dt, int top, int left)
  443. {
  444. int count = 0; //模板表头列数
  445. string[,] arr = null;
  446. DateTime beforeTime;
  447. DateTime afterTime;
  448. // 创建一个Application对象并使其可见
  449. beforeTime = DateTime.Now;
  450. Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application(); //new Excel.ApplicationClass();
  451. app.Visible = true;
  452. afterTime = DateTime.Now;
  453. try
  454. {
  455. // 打开模板文件,得到WorkBook对象
  456. Microsoft.Office.Interop.Excel.Workbook workBook = app.Workbooks._Open(templetFile, missing, missing, missing, missing, missing,
  457. missing, missing, missing, missing, missing, missing, missing);
  458. // 得到WorkSheet对象
  459. Microsoft.Office.Interop.Excel.Worksheet workSheet = (Microsoft.Office.Interop.Excel.Worksheet)workBook.Sheets.get_Item(1);
  460. ArrayList headGourp = new ArrayList();
  461. for (int k = left; k < workSheet.Columns.Count; k++)
  462. {
  463. string head = GetCell_Value(top, k, workSheet);
  464. headGourp.Add(head);
  465. if (head.Equals(""))
  466. {
  467. count = k - left;
  468. break;
  469. }
  470. }
  471. arr = new string[dt.Rows.Count, count];
  472. //读取DataTable数据到二维数组中
  473. for (int k = left, j = 0; k < count + left; k++, j++)
  474. {
  475. string head = headGourp[j].ToString();
  476. //string head = GetCell_Value(top, k, workSheet);
  477. int rows = 0;
  478. for (int i = 0; i < dt.Columns.Count; i++)
  479. {
  480. string dthead = dt.Columns[i].Caption;
  481. if (head.Equals(dthead))
  482. {
  483. foreach (DataRow dr in dt.Rows)
  484. {
  485. arr[rows, k - 1] = dr[i].ToString();
  486. rows++;
  487. }
  488. break;
  489. }
  490. }
  491. }
  492. app.Workbooks.Close();
  493. app.Application.Quit();
  494. app.Quit();
  495. }
  496. catch (Exception ex)
  497. {
  498. ExcelProecssKill(app);
  499. Debug.WriteLine(ex.Message);
  500. return arr;
  501. }
  502. finally
  503. {
  504. ExcelProecssKill(app);
  505. }
  506. return arr;
  507. }
  508. /// <summary>
  509. /// 列标号,Excel最大列数是256
  510. /// </summary>
  511. public static string[] SeqToXlsCol = new string[] {"",
  512. "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
  513. "AA", "AB", "AC", "AD", "AE", "AF", "AG", "AH", "AI", "AJ", "AK", "AL", "AM", "AN", "AO", "AP", "AQ", "AR", "AS", "AT", "AU", "AV", "AW", "AX", "AY", "AZ",
  514. "BA", "BB", "BC", "BD", "BE", "BF", "BG", "BH", "BI", "BJ", "BK", "BL", "BM", "BN", "BO", "BP", "BQ", "BR", "BS", "BT", "BU", "BV", "BW", "BX", "BY", "BZ",
  515. "CA", "CB", "CC", "CD", "CE", "CF", "CG", "CH", "CI", "CJ", "CK", "CL", "CM", "CN", "CO", "CP", "CQ", "CR", "CS", "CT", "CU", "CV", "CW", "CX", "CY", "CZ",
  516. "DA", "DB", "DC", "DD", "DE", "DF", "DG", "DH", "DI", "DJ", "DK", "DL", "DM", "DN", "DO", "DP", "DQ", "DR", "DS", "DT", "DU", "DV", "DW", "DX", "DY", "DZ",
  517. "EA", "EB", "EC", "ED", "EE", "EF", "EG", "EH", "EI", "EJ", "EK", "EL", "EM", "EN", "EO", "EP", "EQ", "ER", "ES", "ET", "EU", "EV", "EW", "EX", "EY", "EZ",
  518. "FA", "FB", "FC", "FD", "FE", "FF", "FG", "FH", "FI", "FJ", "FK", "FL", "FM", "FN", "FO", "FP", "FQ", "FR", "FS", "FT", "FU", "FV", "FW", "FX", "FY", "FZ",
  519. "GA", "GB", "GC", "GD", "GE", "GF", "GG", "GH", "GI", "GJ", "GK", "GL", "GM", "GN", "GO", "GP", "GQ", "GR", "GS", "GT", "GU", "GV", "GW", "GX", "GY", "GZ",
  520. "HA", "HB", "HC", "HD", "HE", "HF", "HG", "HH", "HI", "HJ", "HK", "HL", "HM", "HN", "HO", "HP", "HQ", "HR", "HS", "HT", "HU", "HV", "HW", "HX", "HY", "HZ",
  521. "IA", "IB", "IC", "ID", "IE", "IF", "IG", "IH", "II", "IJ", "IK", "IL", "IM", "IN", "IO", "IP", "IQ", "IR", "IS", "IT", "IU", "IV"
  522. };
  523. /// <summary>
  524. /// 将二维数组 写入 excel
  525. /// </summary>
  526. /// <param name="_BeginPoint">起始位置 如"A1"</param>
  527. /// <param name="_EndPoint">终止位置 如"B5"</param>
  528. /// <param name="_Array_Value">写入的二维数组的值,可以是各种数据类型</param>
  529. /// <returns>bool,是否正确写入</returns>
  530. public bool SetRangeArray_Value(object m_objApp,object m_objSheet,string _BeginPoint, string _EndPoint, object[,] _Array_Value)
  531. {
  532. if (m_objApp == null) { return false; }
  533. if (m_objSheet == null) { return false; }
  534. try
  535. {
  536. //得到range数组
  537. //object[] Parameters_rangeArray = new object[] { "A1", "B5" };
  538. object[] Parameters_rangeArray = new object[] { _BeginPoint, _EndPoint };
  539. object m_objRangeArray = m_objSheet.GetType().InvokeMember("Range", BindingFlags.GetProperty, null, m_objSheet, Parameters_rangeArray);
  540. if (m_objRangeArray == null)
  541. {
  542. Console.WriteLine("出错啦: range == null,请检查range的设置。");
  543. }
  544. //************************
  545. //得到写入值
  546. Object[] ParametersArray_WriteValue = new Object[1];
  547. ParametersArray_WriteValue[0] = _Array_Value; //赋值:数值类型=int
  548. //******************
  549. m_objRangeArray.GetType().InvokeMember("Value2", BindingFlags.SetProperty, null, m_objRangeArray, ParametersArray_WriteValue);
  550. System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objRangeArray);
  551. GC.GetTotalMemory(true);
  552. return true;
  553. }
  554. catch (Exception ex)
  555. {
  556. MessageBox.Show("写入错误!错误原因:" + ex.Message);
  557. return false;
  558. }
  559. }
  560. /// <summary>
  561. /// 退出excel.exe的编辑模式 Edit Mode
  562. /// </summary>
  563. //public void SetApp_Exit_EditMode()
  564. //{
  565. // if (m_objApp == null) { return; }
  566. // if (m_objSheet == null) { return; }
  567. // while (true)
  568. // {
  569. // try
  570. // {
  571. // this.Cursor = System.Windows.Forms.Cursors.WaitCursor;
  572. // bool bAppReady = (bool)m_objApp.GetType().InvokeMember("Ready", BindingFlags.GetProperty, null, m_objApp, null);
  573. // this.Cursor = System.Windows.Forms.Cursors.Arrow;
  574. // break; //如果excel.exe退出了编辑模式则退出循环
  575. // }
  576. // catch
  577. // {
  578. // myWin32API.SetForegroundWindow(this.appSubWinHandle);
  579. // myWin32API.SetFocus(this.appSubWinHandle);
  580. // //System.Threading.Thread.Sleep(100);
  581. // System.Windows.Forms.SendKeys.SendWait("{ESC}"); //发送ESC键
  582. // //System.Windows.Forms.SendKeys.Send("{ESC}"); //发送ESC键
  583. // //System.Threading.Thread.Sleep(100);
  584. // }
  585. // }
  586. //}
  587. }
  588. class ValuesPoint
  589. {
  590. private object values;
  591. public object Values
  592. {
  593. get { return values; }
  594. set { values = value; }
  595. }
  596. private int row;
  597. public int Row
  598. {
  599. get { return row; }
  600. set { row = value; }
  601. }
  602. private int col;
  603. public int Col
  604. {
  605. get { return col; }
  606. set { col = value; }
  607. }
  608. }
  609. }