LeadExcelHelper.cs 25 KB

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