地铁二期项目正式开始

ExcelReadWrite.cs 16KB

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