ExcelHelper.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using Microsoft.Office.Tools.Excel;
  6. using Excel = Microsoft.Office.Interop.Excel;
  7. using System.Data;
  8. using System.Xml.Linq;
  9. namespace Bowin.Common.Utility
  10. {
  11. public enum ExcelFormat
  12. {
  13. Excel95 = Excel.XlFileFormat.xlExcel7,
  14. Excel95_97 = Excel.XlFileFormat.xlExcel9795,
  15. Excel2000_03 = Excel.XlFileFormat.xlExcel8,
  16. Excel2007 = Excel.XlFileFormat.xlExcel12,
  17. Excel2010 = Excel.XlFileFormat.xlExcel4
  18. }
  19. /// <summary>
  20. /// 使用Excel2007 com封装
  21. /// </summary>
  22. public class ExcelHelper
  23. {
  24. /// <summary>
  25. /// excel路径
  26. /// </summary>
  27. public string FilePath { get; set; }
  28. private Excel.Application oXL;
  29. private Excel.Workbook oWB;
  30. private bool isNew = false;
  31. private bool isOpened = false;
  32. public ExcelHelper(string a_filepath = "")
  33. {
  34. FilePath = a_filepath;
  35. }
  36. /// <summary>
  37. /// 打开目标excel
  38. /// </summary>
  39. public void Open()
  40. {
  41. if (oXL != null)
  42. {
  43. throw new Exception("已打开一个Excel文件,请先关闭原文件后再打开新文件");
  44. }
  45. if (string.IsNullOrEmpty(FilePath))
  46. {
  47. throw new Exception("无法找到指定的文件");
  48. }
  49. oXL = new Excel.Application();
  50. oXL.Visible = false;
  51. oXL.DisplayAlerts = false;
  52. oWB = oXL.Workbooks.Open(Filename: FilePath);
  53. isNew = false;
  54. isOpened = true;
  55. }
  56. /// <summary>
  57. /// 创建一份excel
  58. /// </summary>
  59. public void Create()
  60. {
  61. if (oXL != null)
  62. {
  63. throw new Exception("已打开一个Excel文件,请先关闭原文件后再打开新文件");
  64. }
  65. oXL = new Excel.Application();
  66. oXL.Visible = false;
  67. oXL.DisplayAlerts = false;
  68. oWB = oXL.Workbooks.Add();
  69. isNew = true;
  70. isOpened = true;
  71. }
  72. /// <summary>
  73. /// 获取整个excel表数据
  74. /// </summary>
  75. /// <param name="sheetindex"></param>
  76. /// <param name="firstColsName"></param>
  77. /// <returns></returns>
  78. public DataTable getSheetAllDatas(int sheetindex = 1, bool firstColsName = true)
  79. {
  80. var oSheet = oWB.Worksheets.get_Item(sheetindex);
  81. int colslen = oSheet.UsedRange.Cells.Columns.Count;//获得已经用行数
  82. int rowslen = oSheet.UsedRange.Cells.Rows.Count;//获得已经用列数
  83. return getSheetDatas(sheetindex, 0, 0, colslen, rowslen, firstColsName);
  84. }
  85. /// <summary>
  86. /// 获取指定表数据
  87. /// </summary>
  88. /// <param name="sheetindex">工作薄从1开始</param>
  89. /// <param name="colAt">第几列开始,从0开始</param>
  90. /// <param name="rowAt">第几行开始,从0开始</param>
  91. /// <param name="colslen">行数</param>
  92. /// <param name="rowslen">列数</param>
  93. /// <param name="firstRowName">第一行当成数据列名</param>
  94. public DataTable getSheetDatas(int sheetindex = 1, int colAt = 0, int rowAt = 0, int colslen = 1, int rowslen = 1, bool firstColsName = true)
  95. {
  96. if (oWB == null)
  97. {
  98. throw new Exception("没有打开Excel文件");
  99. }
  100. Excel.Worksheet oSheet = oWB.Worksheets.get_Item(sheetindex);
  101. Excel.Range oRng = oSheet.Range[oSheet.Cells[1 + rowAt, 1 + colAt], oSheet.Cells[rowAt + rowslen, colAt + colslen]];
  102. object[,] celldatas = oRng.Value2;
  103. DataTable dt = new DataTable("ExcelCells");
  104. if (celldatas != null && celldatas.Length > 0)
  105. {
  106. int firstrow = 0;
  107. if (firstColsName)
  108. {
  109. for (int i = 1; i <= celldatas.GetLength(1); i++)
  110. {
  111. var celldata = celldatas[1, i];
  112. if (celldata != null)
  113. {
  114. dt.Columns.Add(celldatas[1, i].ToString());
  115. }
  116. }
  117. firstrow = 2;
  118. }
  119. else
  120. {
  121. for (int i = 1; i <= celldatas.GetLength(1); i++)
  122. {
  123. dt.Columns.Add("col" + i.ToString());
  124. }
  125. firstrow = 1;
  126. }
  127. if (celldatas.GetLength(0) >= firstrow)
  128. {
  129. for (int j = firstrow; j <= celldatas.GetLength(0); j++)
  130. {
  131. var newrow = dt.NewRow();
  132. dt.Rows.Add(newrow);
  133. for (int i = 1; i <= dt.Columns.Count; i++)
  134. {
  135. newrow[i - 1] = celldatas[j, i];
  136. }
  137. }
  138. }
  139. }
  140. return dt;
  141. }
  142. /// <summary>
  143. /// 具体格写数据
  144. /// </summary>
  145. /// <param name="sheetindex"></param>
  146. /// <param name="rowIndex"></param>
  147. /// <param name="colIndex"></param>
  148. /// <param name="data"></param>
  149. public void setCell(int sheetindex = 1, int rowIndex = 1, int colIndex = 1, dynamic data = null)
  150. {
  151. Excel.Worksheet oSheet = oWB.Worksheets.get_Item(sheetindex);
  152. oSheet.Cells[rowIndex, colIndex].Value = data;
  153. }
  154. /// <summary>
  155. /// 具体格读数据
  156. /// </summary>
  157. /// <param name="sheetindex"></param>
  158. /// <param name="rowIndex"></param>
  159. /// <param name="colIndex"></param>
  160. /// <returns></returns>
  161. public string getCell(int sheetindex = 1, int rowIndex = 1, int colIndex = 1)
  162. {
  163. Excel.Worksheet oSheet = oWB.Worksheets.get_Item(sheetindex);
  164. return oSheet.Cells[rowIndex, colIndex].Value;
  165. }
  166. /// <summary>
  167. /// 指定一个范围的数据导入
  168. /// </summary>
  169. /// <param name="sheetindex"></param>
  170. /// <param name="colAt"></param>
  171. /// <param name="rowAt"></param>
  172. /// <param name="dtdatas"></param>
  173. public void setSheetDatas(int sheetindex = 1, int colAt = 0, int rowAt = 0, DataTable dtdatas = null)
  174. {
  175. if (dtdatas != null)
  176. {
  177. Excel.Worksheet oSheet = oWB.Worksheets.get_Item(sheetindex);
  178. object[,] ddatas = new object[dtdatas.Rows.Count, dtdatas.Columns.Count];
  179. for (int i = 0; i < dtdatas.Rows.Count; i++)
  180. {
  181. for (int j = 0; j < dtdatas.Columns.Count; j++)
  182. {
  183. ddatas[i, j] = dtdatas.Rows[i][j];
  184. }
  185. }
  186. Excel.Range oRn = oSheet.Range[oSheet.Cells[rowAt + 1, colAt + 1], oSheet.Cells[rowAt + dtdatas.Rows.Count, colAt + dtdatas.Columns.Count]];
  187. oRn.Value2 = ddatas;
  188. //oRn.Columns.AutoFit();
  189. }
  190. }
  191. /// <summary>
  192. /// 设置格字符格式
  193. /// </summary>
  194. /// <param name="sheetindex"></param>
  195. /// <param name="rowbegin"></param>
  196. /// <param name="colbegin"></param>
  197. /// <param name="rowend"></param>
  198. /// <param name="colend"></param>
  199. /// <param name="NumberFormat">1."@" 数字->文本;2."¥#,###.00" 数字-两位小数;3.考虑excel单元格格式</param>
  200. public void setCellsDataFormat(int sheetindex = 1, int rowbegin = 1, int colbegin = 1, int rowend = 1, int colend = 1, string NumberFormat = null)
  201. {
  202. Excel.Worksheet oSheet = oWB.Worksheets.get_Item(sheetindex);
  203. oSheet.Range[oSheet.Cells[rowbegin, colbegin], oSheet.Cells[rowend, colend]].NumberFormat = NumberFormat;
  204. }
  205. /// <summary>
  206. /// 设置列格式
  207. /// </summary>
  208. /// <param name="sheetindex"></param>
  209. /// <param name="colIndex"></param>
  210. /// <param name="NumberFormat">1."@" 数字->文本;2."¥#,###.00" 数字-两位小数;3.考虑excel单元格格式</param>
  211. public void setColsDataFormat(int sheetindex = 1, int colIndex = 1, string NumberFormat = null)
  212. {
  213. Excel.Worksheet oSheet = oWB.Worksheets.get_Item(sheetindex);
  214. Excel.Range oRn = oSheet.Columns[colIndex];
  215. oRn.NumberFormat = NumberFormat;
  216. }
  217. /// <summary>
  218. /// 设置行格式
  219. /// </summary>
  220. /// <param name="sheetindex"></param>
  221. /// <param name="rowIndex"></param>
  222. /// <param name="NumberFormat">1."@" 数字->文本;2."¥#,###.00" 数字-两位小数;3.考虑excel单元格格式</param>
  223. public void setRowsDataFormat(int sheetindex = 1, int rowIndex = 1, string NumberFormat = null)
  224. {
  225. Excel.Worksheet oSheet = oWB.Worksheets.get_Item(sheetindex);
  226. Excel.Range oRn = oSheet.Rows[rowIndex];
  227. oRn.NumberFormat = NumberFormat;
  228. }
  229. /// <summary>
  230. /// 保存excel
  231. /// </summary>
  232. /// <param name="excelformat"></param>
  233. public void Save(ExcelFormat excelformat = ExcelFormat.Excel2000_03)
  234. {
  235. if (string.IsNullOrEmpty(FilePath) || (!isOpened))
  236. {
  237. return;
  238. }
  239. if (isNew)
  240. {
  241. oWB.SaveAs(Filename: FilePath, FileFormat: excelformat);
  242. }
  243. else
  244. {
  245. oWB.Save();
  246. }
  247. }
  248. /// <summary>
  249. /// 另存excel
  250. /// </summary>
  251. /// <param name="fullFileName">新路径</param>
  252. /// <param name="excelformat"></param>
  253. public void SaveAs(string fullFileName, ExcelFormat excelformat = ExcelFormat.Excel2000_03)
  254. {
  255. if (string.IsNullOrEmpty(fullFileName) || (!isOpened))
  256. {
  257. return;
  258. }
  259. oWB.SaveAs(Filename: fullFileName, FileFormat: excelformat);
  260. }
  261. /// <summary>
  262. /// 关闭excel.exe
  263. /// 所有对excel操作都应该调用释放内存
  264. /// </summary>
  265. /// <param name="hasSave"></param>
  266. public void Close(bool hasSave = true)
  267. {
  268. if (oWB != null)
  269. {
  270. oWB.Close(hasSave);
  271. CloseComObj(oWB);
  272. }
  273. if (oXL != null)
  274. {
  275. oXL.Workbooks.Close();
  276. oXL.Quit();
  277. CloseComObj(oXL);
  278. }
  279. GC.Collect();
  280. isOpened = false;
  281. }
  282. private string CloseComObj(object obj)
  283. {
  284. string result = "";
  285. try
  286. {
  287. System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
  288. }
  289. catch (Exception ex)
  290. {
  291. result = ex.Message;
  292. }
  293. finally
  294. {
  295. obj = null;
  296. }
  297. return result;
  298. }
  299. }
  300. }