NxExcelHelper.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743
  1. using NPOI.HSSF.UserModel;
  2. using NPOI.SS.UserModel;
  3. using NPOI.XSSF.UserModel;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Data;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Text;
  10. using System.Windows.Forms;
  11. namespace NXWMS.Client.Code.Extends
  12. {
  13. /// <summary>
  14. /// 使用OPOI导入导出Excel的操作帮助类
  15. /// Copyright20200806 (C) sunyalong
  16. /// 允许修改、添加满足自己项目的需要。
  17. /// 添加、修改后请详细注释。违者会强制删除不予采用。
  18. /// </summary>
  19. public static class NxExcelHelper
  20. {
  21. #region Excel帮助类 私有 操作方法
  22. /// <summary>
  23. /// 获取要保存的文件名称(含完整路径)
  24. /// </summary>
  25. /// <returns></returns>
  26. private static string GetSaveFilePath()
  27. {
  28. SaveFileDialog saveFileDig = new SaveFileDialog();
  29. saveFileDig.Filter = "Excel Office2007及以上(*.xlsx)|*.xlsx|Excel Office97-2003(*.xls)|*.xls";
  30. saveFileDig.FilterIndex = 0;
  31. saveFileDig.Title = "导出到";
  32. saveFileDig.OverwritePrompt = true;
  33. //saveFileDig.InitialDirectory = Common.DesktopDirectory;//设置对话框初始目录
  34. string filePath = null;
  35. if (saveFileDig.ShowDialog() == DialogResult.OK)
  36. {
  37. filePath = saveFileDig.FileName;
  38. }
  39. return filePath;
  40. }
  41. /// <summary>
  42. /// 获取要打开要导入的文件名称(含完整路径)
  43. /// </summary>
  44. /// <returns></returns>
  45. private static string GetOpenFilePath()
  46. {
  47. OpenFileDialog openFileDig = new OpenFileDialog();
  48. openFileDig.Filter = "Excel Office97-2003(*.xls)|*.xls|Excel Office2007及以上(*.xlsx)|*.xlsx";
  49. openFileDig.FilterIndex = 0;
  50. openFileDig.Title = "打开";
  51. openFileDig.CheckFileExists = true;
  52. openFileDig.CheckPathExists = true;
  53. //openFileDig.InitialDirectory = Common.DesktopDirectory;//设置对话框初始目录
  54. string filePath = null;
  55. if (openFileDig.ShowDialog() == DialogResult.OK)
  56. {
  57. filePath = openFileDig.FileName;
  58. }
  59. return filePath;
  60. }
  61. /// <summary>
  62. /// 判断是否为兼容模式(Excel版本.xls或.xlsx)
  63. /// </summary>
  64. /// <param name="filePath">Excel路径文件名称字符串路径</param>
  65. /// <returns></returns>
  66. private static bool GetIsCompatible(string filePath)
  67. {
  68. return filePath.EndsWith(".xls", StringComparison.OrdinalIgnoreCase);
  69. }
  70. /// <summary>
  71. /// 创建工作薄
  72. /// </summary>
  73. /// <param name="isCompatible"> true:Excel Office97-2003; false:Excel Office2007及以上 </param>
  74. /// <returns></returns>
  75. private static IWorkbook CreateWorkbook(bool isCompatible)
  76. {
  77. if (isCompatible)
  78. {
  79. return new HSSFWorkbook();
  80. }
  81. else
  82. {
  83. return new XSSFWorkbook();
  84. }
  85. }
  86. /// <summary>
  87. /// 创建工作薄(依据文件流)
  88. /// </summary>
  89. /// <param name="isCompatible"> true:Excel Office97-2003; false:Excel Office2007及以上 </param>
  90. /// <param name="stream">文件流</param>
  91. /// <returns></returns>
  92. private static IWorkbook CreateWorkbook(bool isCompatible, dynamic stream)
  93. {
  94. if (isCompatible)
  95. {
  96. return new HSSFWorkbook(stream);
  97. }
  98. else
  99. {
  100. return new XSSFWorkbook(stream);
  101. }
  102. }
  103. /// <summary>
  104. /// 创建表格头单元格
  105. /// </summary>
  106. /// <param name="workbook">IWorkbook工作薄</param>
  107. /// <returns></returns>
  108. private static ICellStyle GetCellStyle(IWorkbook workbook)
  109. {
  110. ICellStyle style = workbook.CreateCellStyle();
  111. style.FillPattern = FillPattern.SolidForeground;
  112. style.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Grey25Percent.Index;
  113. return style;
  114. }
  115. /// <summary>
  116. /// 从工作表中生成DataTable
  117. /// </summary>
  118. /// <param name="sheet">工作表</param>
  119. /// <param name="headerRowIndex">行索引</param>
  120. /// <returns></returns>
  121. private static DataTable GetDataTableFromSheet(ISheet sheet, int headerRowIndex)
  122. {
  123. DataTable table = new DataTable();
  124. IRow headerRow = sheet.GetRow(headerRowIndex);
  125. int cellCount = headerRow.LastCellNum;
  126. for (int i = headerRow.FirstCellNum; i < cellCount; i++)
  127. {
  128. if (headerRow.GetCell(i) == null || headerRow.GetCell(i).StringCellValue.Trim() == "")
  129. {
  130. // 如果遇到第一个空列,则不再继续向后读取
  131. cellCount = i;
  132. break;
  133. }
  134. DataColumn column = new DataColumn(headerRow.GetCell(i).StringCellValue);
  135. table.Columns.Add(column);
  136. }
  137. for (int i = (headerRowIndex + 1); i <= sheet.LastRowNum; i++)
  138. {
  139. IRow row = sheet.GetRow(i);
  140. //如果遇到某行的第一个单元格的值为空,则不再继续向下读取
  141. if (row != null && !string.IsNullOrEmpty(row.GetCell(0).ToString()))
  142. {
  143. DataRow dataRow = table.NewRow();
  144. for (int j = row.FirstCellNum; j < cellCount; j++)
  145. {
  146. dataRow[j] = row.GetCell(j).ToString();
  147. }
  148. table.Rows.Add(dataRow);
  149. }
  150. }
  151. return table;
  152. }
  153. #region 20191116 孙亚龙针对电池测试数据表格开发的方法
  154. private static DataTable GetDataTableFromSheet(ISheet sheet, int headerRowIndex, ref string ipStr, ref string timeStr)
  155. {
  156. DataTable table = new DataTable();
  157. IRow headerRow = sheet.GetRow(headerRowIndex);
  158. int cellCount = headerRow.LastCellNum;
  159. #region 获取行索引为1、2的值
  160. IRow indexRow1 = sheet.GetRow(1);
  161. IRow indexRow2 = sheet.GetRow(2);
  162. ipStr = indexRow1.GetCell(0).StringCellValue.Split(':')[1];
  163. timeStr = indexRow2.GetCell(0).StringCellValue.Split(':')[1];
  164. #endregion
  165. for (int i = headerRow.FirstCellNum; i < cellCount; i++)
  166. {
  167. if (headerRow.GetCell(i) == null || headerRow.GetCell(i).StringCellValue.Trim() == "")
  168. {
  169. // 如果遇到第一个空列,则不再继续向后读取
  170. cellCount = i;
  171. break;
  172. }
  173. DataColumn column = new DataColumn(headerRow.GetCell(i).StringCellValue);
  174. table.Columns.Add(column);
  175. }
  176. for (int i = (headerRowIndex + 1); i <= sheet.LastRowNum; i++)
  177. {
  178. IRow row = sheet.GetRow(i);
  179. //如果遇到某行的第一个单元格的值为空,则不再继续向下读取
  180. if (row != null && !string.IsNullOrEmpty(row.GetCell(0).ToString()))
  181. {
  182. DataRow dataRow = table.NewRow();
  183. for (int j = row.FirstCellNum; j < cellCount; j++)
  184. {
  185. dataRow[j] = row.GetCell(j).ToString();
  186. }
  187. table.Rows.Add(dataRow);
  188. }
  189. }
  190. return table;
  191. }
  192. public static DataSet ImportFromExcel(string excelFilePath, int headerRowIndex, ref string ipStr, ref string timeStr)
  193. {
  194. if (string.IsNullOrEmpty(excelFilePath))
  195. {
  196. excelFilePath = GetOpenFilePath();
  197. }
  198. if (string.IsNullOrEmpty(excelFilePath))
  199. {
  200. return null;
  201. }
  202. using (FileStream stream = System.IO.File.OpenRead(excelFilePath))
  203. {
  204. bool isCompatible = GetIsCompatible(excelFilePath);
  205. return ImportFromExcel(stream, headerRowIndex, isCompatible, ref ipStr, ref timeStr);
  206. }
  207. }
  208. public static DataSet ImportFromExcel(Stream excelFileStream, int headerRowIndex, bool isCompatible, ref string ipStr, ref string timeStr)
  209. {
  210. DataSet ds = new DataSet();
  211. IWorkbook workbook = CreateWorkbook(isCompatible, excelFileStream);
  212. for (int i = 0; i < workbook.NumberOfSheets; i++)
  213. {
  214. ISheet sheet = workbook.GetSheetAt(i);
  215. DataTable table = GetDataTableFromSheet(sheet, headerRowIndex, ref ipStr, ref timeStr);
  216. ds.Tables.Add(table);
  217. }
  218. excelFileStream.Close();
  219. workbook = null;
  220. return ds;
  221. }
  222. #endregion
  223. #endregion
  224. #region Excel帮助类 公共 导出方法
  225. /// <summary>
  226. /// 由DataSet导出为Excel
  227. /// </summary>
  228. /// <param name="sourceDs">要导出的DataSet</param>
  229. /// <param name="filePath">Excel文件存放路径</param>
  230. /// <returns>Excel文件存放路径</returns>
  231. public static string ExportToExcel(DataSet sourceDs, string filePath = null)
  232. {
  233. if (string.IsNullOrEmpty(filePath))
  234. {
  235. filePath = GetSaveFilePath();
  236. }
  237. if (string.IsNullOrEmpty(filePath))
  238. {
  239. return null;
  240. }
  241. bool isCompatible = GetIsCompatible(filePath);
  242. IWorkbook workbook = CreateWorkbook(isCompatible);
  243. ICellStyle cellStyle = GetCellStyle(workbook);
  244. for (int i = 0; i < sourceDs.Tables.Count; i++)
  245. {
  246. DataTable table = sourceDs.Tables[i];
  247. string sheetName = "result" + i.ToString();
  248. ISheet sheet = workbook.CreateSheet(sheetName);
  249. IRow headerRow = sheet.CreateRow(0);
  250. // handling header.
  251. foreach (DataColumn column in table.Columns)
  252. {
  253. ICell cell = headerRow.CreateCell(column.Ordinal);
  254. cell.SetCellValue(column.ColumnName);
  255. cell.CellStyle = cellStyle;
  256. }
  257. // handling value.
  258. int rowIndex = 1;
  259. foreach (DataRow row in table.Rows)
  260. {
  261. IRow dataRow = sheet.CreateRow(rowIndex);
  262. foreach (DataColumn column in table.Columns)
  263. {
  264. dataRow.CreateCell(column.Ordinal).SetCellValue((row[column] ?? "").ToString());
  265. }
  266. rowIndex++;
  267. }
  268. }
  269. FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
  270. workbook.Write(fs);
  271. fs.Dispose();
  272. workbook = null;
  273. return filePath;
  274. }
  275. /// <summary>
  276. /// 由DataTable导出Excel
  277. /// </summary>
  278. /// <param name="sourceTable">要导出数据的DataTable</param>
  279. /// <param name="sheetName">工作表名称</param>
  280. /// <param name="filePath">Excel文件存放路径</param>
  281. /// <returns>Excel文件存放路径</returns>
  282. public static string ExportToExcel(DataTable sourceTable, string sheetName = "result", string filePath = null)
  283. {
  284. if (sourceTable.Rows.Count <= 0) return null;
  285. if (string.IsNullOrEmpty(filePath))
  286. {
  287. filePath = GetSaveFilePath();
  288. }
  289. if (string.IsNullOrEmpty(filePath)) return null;
  290. bool isCompatible = GetIsCompatible(filePath);
  291. IWorkbook workbook = CreateWorkbook(isCompatible);
  292. ICellStyle cellStyle = GetCellStyle(workbook);
  293. ISheet sheet = workbook.CreateSheet(sheetName);
  294. IRow headerRow = sheet.CreateRow(0);
  295. // handling header.
  296. foreach (DataColumn column in sourceTable.Columns)
  297. {
  298. ICell headerCell = headerRow.CreateCell(column.Ordinal);
  299. headerCell.SetCellValue(column.ColumnName);
  300. headerCell.CellStyle = cellStyle;
  301. }
  302. // handling value.
  303. int rowIndex = 1;
  304. foreach (DataRow row in sourceTable.Rows)
  305. {
  306. IRow dataRow = sheet.CreateRow(rowIndex);
  307. foreach (DataColumn column in sourceTable.Columns)
  308. {
  309. dataRow.CreateCell(column.Ordinal).SetCellValue((row[column] ?? "").ToString());
  310. }
  311. rowIndex++;
  312. }
  313. FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
  314. workbook.Write(fs);
  315. fs.Dispose();
  316. sheet = null;
  317. headerRow = null;
  318. workbook = null;
  319. return filePath;
  320. }
  321. /// <summary>
  322. /// 实体类List集合导出为Excel
  323. /// </summary>
  324. /// <typeparam name="T">实体类类型</typeparam>
  325. /// <param name="data">实体类List集合数据</param>
  326. /// <param name="headerNameList">实体类属性的键值对集合</param>
  327. /// <param name="sheetName">工作表名称</param>
  328. /// <param name="filePath">Excel文件存放路径</param>
  329. /// <returns>Excel文件存放路径</returns>
  330. public static string ExportToExcel<T>(List<T> data, IList<KeyValuePair<string, string>> headerNameList, string sheetName = "result", string filePath = null) where T : class
  331. {
  332. if (data.Count <= 0) return null;
  333. if (string.IsNullOrEmpty(filePath))
  334. {
  335. filePath = GetSaveFilePath();
  336. }
  337. if (string.IsNullOrEmpty(filePath)) return null;
  338. bool isCompatible = GetIsCompatible(filePath);
  339. IWorkbook workbook = CreateWorkbook(isCompatible);
  340. ICellStyle cellStyle = GetCellStyle(workbook);
  341. ISheet sheet = workbook.CreateSheet(sheetName);
  342. IRow headerRow = sheet.CreateRow(0);
  343. for (int i = 0; i < headerNameList.Count; i++)
  344. {
  345. ICell cell = headerRow.CreateCell(i);
  346. cell.SetCellValue(headerNameList[i].Value);
  347. cell.CellStyle = cellStyle;
  348. }
  349. Type t = typeof(T);
  350. int rowIndex = 1;
  351. foreach (T item in data)
  352. {
  353. IRow dataRow = sheet.CreateRow(rowIndex);
  354. for (int n = 0; n < headerNameList.Count; n++)
  355. {
  356. object pValue = t.GetProperty(headerNameList[n].Key).GetValue(item, null);
  357. dataRow.CreateCell(n).SetCellValue((pValue ?? "").ToString());
  358. }
  359. rowIndex++;
  360. }
  361. FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
  362. workbook.Write(fs);
  363. fs.Dispose();
  364. sheet = null;
  365. headerRow = null;
  366. workbook = null;
  367. return filePath;
  368. }
  369. /// <summary>
  370. /// 由DataGridView导出为Excel
  371. /// </summary>
  372. /// <param name="grid">DataGridView对象</param>
  373. /// <param name="sheetName">工作表名称</param>
  374. /// <param name="filePath">Excel文件存放路径</param>
  375. /// <returns>Excel文件存放路径</returns>
  376. public static string ExportToExcel(DataGridView grid, string sheetName = "result", string filePath = null)
  377. {
  378. if (grid.Rows.Count <= 0) return null;
  379. if (string.IsNullOrEmpty(filePath))
  380. {
  381. filePath = GetSaveFilePath();
  382. }
  383. if (string.IsNullOrEmpty(filePath)) return null;
  384. bool isCompatible = GetIsCompatible(filePath);
  385. IWorkbook workbook = CreateWorkbook(isCompatible);
  386. ICellStyle cellStyle = GetCellStyle(workbook);
  387. ISheet sheet = workbook.CreateSheet(sheetName);
  388. IRow headerRow = sheet.CreateRow(0);
  389. for (int i = 0; i < grid.Columns.Count; i++)
  390. {
  391. ICell cell = headerRow.CreateCell(i);
  392. cell.SetCellValue(grid.Columns[i].HeaderText);
  393. cell.CellStyle = cellStyle;
  394. }
  395. int rowIndex = 1;
  396. foreach (DataGridViewRow row in grid.Rows)
  397. {
  398. IRow dataRow = sheet.CreateRow(rowIndex);
  399. for (int n = 0; n < grid.Columns.Count; n++)
  400. {
  401. dataRow.CreateCell(n).SetCellValue((row.Cells[n].Value ?? "").ToString());
  402. }
  403. rowIndex++;
  404. }
  405. FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
  406. workbook.Write(fs);
  407. fs.Dispose();
  408. sheet = null;
  409. headerRow = null;
  410. workbook = null;
  411. return filePath;
  412. }
  413. #endregion
  414. #region Excel帮助类 公共 导入方法
  415. /// <summary>
  416. /// 由Excel文件流导入DataTable
  417. /// </summary>
  418. /// <param name="excelFileStream">Excel文件流</param>
  419. /// <param name="sheetName">Excel工作表名称</param>
  420. /// <param name="headerRowIndex">Excel表头行索引</param>
  421. /// <param name="isCompatible">是否为兼容模式</param>
  422. /// <returns>DataTable</returns>
  423. public static DataTable ImportFromExcel(Stream excelFileStream, string sheetName, int headerRowIndex, bool isCompatible)
  424. {
  425. IWorkbook workbook = CreateWorkbook(isCompatible, excelFileStream);
  426. ISheet sheet = null;
  427. int sheetIndex = -1;
  428. if (int.TryParse(sheetName, out sheetIndex))
  429. {
  430. sheet = workbook.GetSheetAt(sheetIndex);
  431. }
  432. else
  433. {
  434. sheet = workbook.GetSheet(sheetName);
  435. }
  436. DataTable table = GetDataTableFromSheet(sheet, headerRowIndex);
  437. excelFileStream.Close();
  438. workbook = null;
  439. sheet = null;
  440. return table;
  441. }
  442. /// <summary>
  443. /// 由Excel导入DataTable
  444. /// </summary>
  445. /// <param name="excelFilePath">Excel文件路径,为物理路径。</param>
  446. /// <param name="sheetName">Excel工作表名称</param>
  447. /// <param name="headerRowIndex">Excel表头行索引</param>
  448. /// <returns>DataTable</returns>
  449. public static DataTable ImportFromExcel(string excelFilePath, string sheetName, int headerRowIndex)
  450. {
  451. if (string.IsNullOrEmpty(excelFilePath))
  452. {
  453. excelFilePath = GetOpenFilePath();
  454. }
  455. if (string.IsNullOrEmpty(excelFilePath))
  456. {
  457. return null;
  458. }
  459. using (FileStream stream = System.IO.File.OpenRead(excelFilePath))
  460. {
  461. bool isCompatible = GetIsCompatible(excelFilePath);
  462. return ImportFromExcel(stream, sheetName, headerRowIndex, isCompatible);
  463. }
  464. }
  465. /// <summary>
  466. /// 由Excel文件流导入DataSet,如果有多个工作表,则导入多个DataTable
  467. /// </summary>
  468. /// <param name="excelFileStream">Excel文件流</param>
  469. /// <param name="headerRowIndex">Excel表头行索引</param>
  470. /// <param name="isCompatible">是否为兼容模式</param>
  471. /// <returns>DataSet</returns>
  472. public static DataSet ImportFromExcel(Stream excelFileStream, int headerRowIndex, bool isCompatible)
  473. {
  474. DataSet ds = new DataSet();
  475. IWorkbook workbook = CreateWorkbook(isCompatible, excelFileStream);
  476. for (int i = 0; i < workbook.NumberOfSheets; i++)
  477. {
  478. ISheet sheet = workbook.GetSheetAt(i);
  479. DataTable table = GetDataTableFromSheet(sheet, headerRowIndex);
  480. ds.Tables.Add(table);
  481. }
  482. excelFileStream.Close();
  483. workbook = null;
  484. return ds;
  485. }
  486. /// <summary>
  487. /// 由Excel文件导入DataSet,如果有多个工作表,则导入多个DataTable
  488. /// </summary>
  489. /// <param name="excelFilePath">Excel文件路径,为物理路径。</param>
  490. /// <param name="headerRowIndex">Excel表头行索引</param>
  491. /// <returns>DataSet</returns>
  492. public static DataSet ImportFromExcel(string excelFilePath, int headerRowIndex)
  493. {
  494. if (string.IsNullOrEmpty(excelFilePath))
  495. {
  496. excelFilePath = GetOpenFilePath();
  497. }
  498. if (string.IsNullOrEmpty(excelFilePath))
  499. {
  500. return null;
  501. }
  502. using (FileStream stream = System.IO.File.OpenRead(excelFilePath))
  503. {
  504. bool isCompatible = GetIsCompatible(excelFilePath);
  505. return ImportFromExcel(stream, headerRowIndex, isCompatible);
  506. }
  507. }
  508. #endregion
  509. #region Excel帮助类 公共 转换方法
  510. /// <summary>
  511. /// 将Excel的列索引转换为列名,列索引从0开始,列名从A开始。如第0列为A,第1列为B...
  512. /// </summary>
  513. /// <param name="index">列索引</param>
  514. /// <returns>列名,如第0列为A,第1列为B...</returns>
  515. public static string ConvertColumnIndexToColumnName(int index)
  516. {
  517. index = index + 1;
  518. int system = 26;
  519. char[] digArray = new char[100];
  520. int i = 0;
  521. while (index > 0)
  522. {
  523. int mod = index % system;
  524. if (mod == 0) mod = system;
  525. digArray[i++] = (char)(mod - 1 + 'A');
  526. index = (index - 1) / 26;
  527. }
  528. StringBuilder sb = new StringBuilder(i);
  529. for (int j = i - 1; j >= 0; j--)
  530. {
  531. sb.Append(digArray[j]);
  532. }
  533. return sb.ToString();
  534. }
  535. /// <summary>
  536. /// 转化日期
  537. /// </summary>
  538. /// <param name="date">日期</param>
  539. /// <returns></returns>
  540. public static DateTime ConvertToDate(object date)
  541. {
  542. string dtStr = (date ?? "").ToString();
  543. DateTime dt = new DateTime();
  544. if (DateTime.TryParse(dtStr, out dt))
  545. {
  546. return dt;
  547. }
  548. try
  549. {
  550. string spStr = "";
  551. if (dtStr.Contains("-"))
  552. {
  553. spStr = "-";
  554. }
  555. else if (dtStr.Contains("/"))
  556. {
  557. spStr = "/";
  558. }
  559. string[] time = dtStr.Split(spStr.ToCharArray());
  560. int year = Convert.ToInt32(time[2]);
  561. int month = Convert.ToInt32(time[0]);
  562. int day = Convert.ToInt32(time[1]);
  563. string years = Convert.ToString(year);
  564. string months = Convert.ToString(month);
  565. string days = Convert.ToString(day);
  566. if (months.Length == 4)
  567. {
  568. dt = Convert.ToDateTime(date);
  569. }
  570. else
  571. {
  572. string rq = "";
  573. if (years.Length == 1)
  574. {
  575. years = "0" + years;
  576. }
  577. if (months.Length == 1)
  578. {
  579. months = "0" + months;
  580. }
  581. if (days.Length == 1)
  582. {
  583. days = "0" + days;
  584. }
  585. rq = "20" + years + "-" + months + "-" + days;
  586. dt = Convert.ToDateTime(rq);
  587. }
  588. }
  589. catch
  590. {
  591. throw new Exception("日期格式不正确,转换日期类型失败!");
  592. }
  593. return dt;
  594. }
  595. /// <summary>
  596. /// 转化数字
  597. /// </summary>
  598. /// <param name="d">数字字符串</param>
  599. /// <returns></returns>
  600. public static decimal ConvertToDecimal(object d)
  601. {
  602. string dStr = (d ?? "").ToString();
  603. decimal result = 0;
  604. if (decimal.TryParse(dStr, out result))
  605. {
  606. return result;
  607. }
  608. else
  609. {
  610. throw new Exception("数字格式不正确,转换数字类型失败!");
  611. }
  612. }
  613. /// <summary>
  614. /// 转化布尔
  615. /// </summary>
  616. /// <param name="b"></param>
  617. /// <returns></returns>
  618. public static bool ConvertToBoolen(object b)
  619. {
  620. string bStr = (b ?? "").ToString().Trim();
  621. bool result = false;
  622. if (bool.TryParse(bStr, out result))
  623. {
  624. return result;
  625. }
  626. else if (bStr == "0" || bStr == "1")
  627. {
  628. return (bStr == "0");
  629. }
  630. else
  631. {
  632. throw new Exception("布尔格式不正确,转换布尔类型失败!");
  633. }
  634. }
  635. #endregion
  636. }
  637. }