地铁二期项目正式开始

ExcelReadWrite.cs 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. using Microsoft.Win32;
  2. using NPOI.HSSF.UserModel;
  3. using NPOI.SS.UserModel;
  4. using NPOI.XSSF.UserModel;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Data;
  8. using System.IO;
  9. using System.Linq;
  10. using System.Text;
  11. using System.Web;
  12. namespace YTSoft.Common
  13. {
  14. public class ExcelReadWrite
  15. {
  16. /// <summary>
  17. /// 将DataTable数据导入到excel中
  18. /// </summary>
  19. /// <param name="data">要导入的数据</param>
  20. /// <param name="isColumnWritten">DataTable的列名是否要导入</param>
  21. /// <param name="sheetName">要导入的excel的sheet的名称</param>
  22. /// <returns>导入数据行数(包含列名那一行)</returns>
  23. public IWorkbook DataTableToExcel(DataTable data, string sheetName, bool isColumnWritten)
  24. {
  25. int i = 0;
  26. int j = 0;
  27. int count = 0;
  28. IWorkbook workbook = null;
  29. ISheet sheet = null;
  30. try
  31. {
  32. if (OfficeType() == 1)// 2003版本
  33. {
  34. workbook = new HSSFWorkbook();
  35. }
  36. else // 2007版本
  37. {
  38. workbook = new XSSFWorkbook();
  39. }
  40. if (workbook != null)
  41. {
  42. sheet = workbook.CreateSheet(sheetName);
  43. }
  44. else
  45. {
  46. return null;
  47. }
  48. //表头字段样式
  49. ICellStyle styletitlehead = workbook.CreateCellStyle();
  50. styletitlehead.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
  51. styletitlehead.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;
  52. IFont fonthead = workbook.CreateFont();
  53. fonthead.Color = 0;
  54. fonthead.IsBold = true;
  55. styletitlehead.SetFont(fonthead);
  56. //分录字段样式
  57. ICellStyle styletitledetail = workbook.CreateCellStyle();
  58. styletitledetail.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
  59. styletitledetail.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;
  60. IFont fontdetail = workbook.CreateFont();
  61. fontdetail.Color = 3;
  62. styletitledetail.SetFont(fontdetail);
  63. if (isColumnWritten == true) //写入DataTable的列名
  64. {
  65. IRow row = sheet.CreateRow(0);
  66. for (j = 0; j < data.Columns.Count; j++)
  67. {
  68. if (data.ExtendedProperties.Contains(data.Columns[j].ColumnName))
  69. {
  70. if (data.ExtendedProperties[data.Columns[j].ColumnName].ToString() == "分录")
  71. {
  72. row.CreateCell(j).SetCellValue(data.Columns[j].ColumnName);
  73. row.GetCell(j).CellStyle = styletitledetail;
  74. row.GetCell(j).SetCellType(CellType.String);
  75. }
  76. }
  77. else
  78. {
  79. row.CreateCell(j).SetCellValue(data.Columns[j].ColumnName);
  80. row.GetCell(j).CellStyle = styletitlehead;
  81. row.GetCell(j).SetCellType(CellType.String);
  82. }
  83. }
  84. count = 1;
  85. }
  86. else
  87. {
  88. count = 0;
  89. }
  90. for (i = 0; i < data.Rows.Count; i++)
  91. {
  92. IRow row = sheet.CreateRow(count);
  93. for (j = 0; j < data.Columns.Count; j++)
  94. {
  95. row.CreateCell(j).SetCellValue(data.Rows[i][j].ToString());
  96. }
  97. count++;
  98. }
  99. sheet.CreateFreezePane(0, 1, 0, 1);
  100. ICellStyle styleconet = workbook.CreateCellStyle();
  101. styleconet.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Left;
  102. styleconet.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;
  103. IFont fontconet = workbook.CreateFont();
  104. fontconet.FontHeightInPoints = 14;
  105. styleconet.SetFont(fontconet);
  106. IDataFormat dataformat = workbook.CreateDataFormat();
  107. styleconet.DataFormat = dataformat.GetFormat("@");
  108. #region 获取当前列的宽度,然后对比本列的长度,取最大值
  109. //列宽自适应,只对英文和数字有效
  110. for (i = 0; i <= data.Columns.Count; i++)
  111. {
  112. sheet.AutoSizeColumn(i);
  113. sheet.SetDefaultColumnStyle(i, styleconet);
  114. }
  115. for (int columnNum = 0; columnNum < data.Columns.Count; columnNum++)
  116. {
  117. int columnWidth = sheet.GetColumnWidth(columnNum) / 256;
  118. for (int rowNum = 0; rowNum <= sheet.LastRowNum; rowNum++)
  119. {
  120. IRow currentRow;
  121. //当前行未被使用过
  122. if (sheet.GetRow(rowNum) == null)
  123. {
  124. currentRow = sheet.CreateRow(rowNum);
  125. }
  126. else
  127. {
  128. currentRow = sheet.GetRow(rowNum);
  129. }
  130. if (currentRow.GetCell(columnNum) != null)
  131. {
  132. ICell currentCell = currentRow.GetCell(columnNum);
  133. if (currentCell != null)
  134. {
  135. int length = Encoding.Default.GetBytes(currentCell.ToString()).Length;
  136. if (columnWidth < length)
  137. {
  138. columnWidth = length;
  139. }
  140. }
  141. }
  142. }
  143. if (columnWidth>100)
  144. {
  145. columnWidth = 100;
  146. }
  147. sheet.SetColumnWidth(columnNum, columnWidth * 256);
  148. }
  149. #endregion
  150. return workbook;
  151. }
  152. catch (Exception ex)
  153. {
  154. return null;
  155. }
  156. }
  157. public byte[] GetExcelByte(DataTable data, string sheetName, bool isColumnWritten)
  158. {
  159. IWorkbook workbook = DataTableToExcel(data, sheetName, isColumnWritten);
  160. var ms = new NpoiMemoryStream();
  161. ms.AllowClose = false;
  162. workbook.Write(ms);
  163. ms.Flush();
  164. ms.Seek(0, SeekOrigin.Begin);
  165. byte[] bytes = new byte[ms.Length];
  166. ms.Read(bytes, 0, bytes.Length);
  167. // 设置当前流的位置为流的开始
  168. ms.Seek(0, SeekOrigin.Begin);
  169. ms.AllowClose = true;
  170. return bytes;
  171. }
  172. public NpoiMemoryStream GetExcelMemoryStream(DataTable data, string sheetName, bool isColumnWritten)
  173. {
  174. IWorkbook workbook = DataTableToExcel(data, sheetName, isColumnWritten);
  175. var ms = new NpoiMemoryStream();
  176. ms.AllowClose = false;
  177. workbook.Write(ms);
  178. ms.Flush();
  179. ms.Seek(0, SeekOrigin.Begin);
  180. ms.AllowClose = true;
  181. return ms;
  182. }
  183. /// <summary>
  184. /// 重写Npoi流方法
  185. /// </summary>
  186. public class NpoiMemoryStream : MemoryStream
  187. {
  188. public NpoiMemoryStream()
  189. {
  190. AllowClose = true;
  191. }
  192. public bool AllowClose { get; set; }
  193. public override void Close()
  194. {
  195. if (AllowClose)
  196. base.Close();
  197. }
  198. }
  199. /// <summary>
  200. /// 将excel中的数据导入到DataTable中
  201. /// </summary>
  202. /// <param name ="path">excel文件路径含excel文件名称及后缀</param>
  203. /// <param name="sheetname">excel工作薄sheet的名称</param>
  204. /// <param name="isFirstRowColumn">第一行是否是DataTable的列名</param>
  205. /// <returns>返回的DataTable</returns>
  206. public DataTable LoadExcel(Stream streamfile, bool isFirstRowColumn)
  207. {
  208. ISheet sheet = null;
  209. IWorkbook workbook = null;
  210. DataTable data = new DataTable();
  211. try
  212. {
  213. //if (fileName.IndexOf(".xlsx") > 0) // 2007版本
  214. //{
  215. // workbook = new XSSFWorkbook(streamfile);
  216. //}
  217. //else if (fileName.IndexOf(".xls") > 0)// 2003版本
  218. //{
  219. // workbook = new HSSFWorkbook(streamfile);
  220. //}
  221. //else
  222. //{
  223. // return null;
  224. //}
  225. try
  226. {
  227. workbook = new XSSFWorkbook(streamfile);
  228. }
  229. catch (Exception ex)
  230. {
  231. workbook = new HSSFWorkbook(streamfile);
  232. }
  233. sheet = workbook.GetSheetAt(0);
  234. IRow firstRow = sheet.GetRow(0);
  235. int cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数
  236. int rowCount = sheet.LastRowNum; //一列最后一个cell的编号 即总的行数
  237. int startRow = 0;
  238. if (isFirstRowColumn)
  239. {
  240. for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
  241. {
  242. ICell cell = firstRow.GetCell(i);
  243. if (cell != null)
  244. {
  245. string cellValue = cell.StringCellValue;
  246. if (cellValue != null)
  247. {
  248. DataColumn column = new DataColumn(cellValue);
  249. data.Columns.Add(column);
  250. }
  251. }
  252. }
  253. startRow = sheet.FirstRowNum + 1;
  254. }
  255. else
  256. {
  257. startRow = sheet.FirstRowNum;
  258. }
  259. //Execel第一行是标题,不是要导入数据库的数据
  260. for (int i = startRow; i <= rowCount; i++)
  261. {
  262. IRow row = sheet.GetRow(i);
  263. if (row == null) continue; //没有数据的行默认是null 
  264. DataRow dataRow = data.NewRow();
  265. for (int j = row.FirstCellNum; j <= cellCount; j++)
  266. {
  267. if (i == startRow && data.Columns.Count < cellCount)
  268. {
  269. DataColumn column = new DataColumn(row.GetCell(j).ToString());
  270. data.Columns.Add(column);
  271. }
  272. if (row.GetCell(j) != null) //同理,没有数据的单元格都默认是null
  273. dataRow[j] = row.GetCell(j).ToString();
  274. }
  275. data.Rows.Add(dataRow);
  276. }
  277. return data;
  278. }
  279. catch (Exception ex)
  280. {
  281. return null;
  282. }
  283. }
  284. /// <summary>
  285. /// 判断office版本
  286. /// 返回0为07及以上版本,返回1为03及以下版本
  287. /// </summary>
  288. /// <returns></returns>
  289. public int OfficeType()
  290. {
  291. int type = 1;
  292. RegistryKey rk = Registry.LocalMachine;
  293. //office 2003
  294. RegistryKey office2003 = rk.OpenSubKey(@"SOFTWARE\\Microsoft\\Office\\11.0\\Word\\InstallRoot\\");
  295. //office 97
  296. RegistryKey office97 = rk.OpenSubKey(@"SOFTWARE\\Microsoft\\Office\\8.0\\Word\\InstallRoot\\");
  297. //office 2000
  298. RegistryKey office2000 = rk.OpenSubKey(@"SOFTWARE\\Microsoft\\Office\\9.0\\Word\\InstallRoot\\");
  299. //office xp
  300. RegistryKey officexp = rk.OpenSubKey(@"SOFTWARE\\Microsoft\\Office\\10.0\\Word\\InstallRoot\\");
  301. //07
  302. RegistryKey f07 = rk.OpenSubKey(@"SOFTWARE\Microsoft\Office\12.0\Excel\InstallRoot\");
  303. //10
  304. RegistryKey office2010 = rk.OpenSubKey(@"SOFTWARE\Microsoft\Office\14.0\Common\InstallRoot");
  305. //13
  306. RegistryKey office2013 = rk.OpenSubKey(@"SOFTWARE\Microsoft\Office\15.0\Common\InstallRoot");
  307. ////查询wps
  308. RegistryKey wps = rk.OpenSubKey(@"SOFTWARE\Kingsoft\Office\6.0\common\");
  309. if (officexp != null)
  310. {
  311. string filexp = officexp.GetValue("Path").ToString();
  312. if (File.Exists(filexp + "Excel.exe"))
  313. {
  314. type = 1;
  315. }
  316. }
  317. if (office2000 != null)
  318. {
  319. string file2000 = officexp.GetValue("Path").ToString();
  320. if (File.Exists(file2000 + "Excel.exe"))
  321. {
  322. type = 1;
  323. }
  324. }
  325. if (office97 != null)
  326. {
  327. string file97 = officexp.GetValue("Path").ToString();
  328. if (File.Exists(file97 + "Excel.exe"))
  329. {
  330. type = 1;
  331. }
  332. }
  333. if (office2003 != null)
  334. {
  335. string file2003 = officexp.GetValue("Path").ToString();
  336. if (File.Exists(file2003 + "Excel.exe"))
  337. {
  338. type = 1;
  339. }
  340. }
  341. if (f07 != null)
  342. {
  343. string file2007 = f07.GetValue("Path").ToString();
  344. if (File.Exists(file2007 + "Excel.exe"))
  345. {
  346. type = 2;
  347. }
  348. }
  349. if (office2010 != null)
  350. {
  351. string file2010 = office2010.GetValue("Path").ToString();
  352. if (File.Exists(file2010 + "Excel.exe"))
  353. {
  354. type = 3;
  355. }
  356. }
  357. if (office2013 != null)
  358. {
  359. string file2013 = office2013.GetValue("Path").ToString();
  360. if (File.Exists(file2013 + "Excel.exe"))
  361. {
  362. type = 3;
  363. }
  364. }
  365. //if (wps != null)
  366. //{
  367. // string filewps = wps.GetValue("Path").ToString();
  368. // if (File.Exists(filewps + "Excel.exe"))
  369. // {
  370. // type = 1;
  371. // }
  372. //}
  373. return type;
  374. }
  375. }
  376. }