TZCommonFunc.cs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.Data.OleDb;
  5. using System.Linq;
  6. using System.Reflection;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using System.Windows.Forms;
  10. using Uninpho.DBOperation.Model;
  11. using ClosedXML.Excel;
  12. using System.IO;
  13. using DevExpress.XtraEditors;
  14. namespace Uninpho.Tools.components
  15. {
  16. class catchExcelError
  17. {
  18. public int row;
  19. public int column;
  20. public string message;
  21. }
  22. /// <summary>
  23. /// 公共函数类
  24. /// 保存通用数据
  25. /// </summary>
  26. static class TZCommonFunc
  27. {
  28. private static string[] ErrorM = new string[] { "不能为空", "数字格式错误","未知错误" };
  29. //excel数据规范异常记录
  30. private static List<catchExcelError> dataError = new List<catchExcelError>();
  31. public static List<string> dataSsccess = new List<string>();
  32. //public static List<T_quxian_account> Listdata_qx { get; set; }
  33. //public static List<T_daocha_account> Listdata_dc { get; set; }
  34. //public static List<T_guanjie_account> Listdata_gj { get; set; }
  35. public static List<T_quxian_account> Listdata_qx = new List<T_quxian_account>();
  36. public static List<T_daocha_account> Listdata_dc = new List<T_daocha_account>();
  37. public static List<T_guanjie_account> Listdata_gj = new List<T_guanjie_account>();
  38. public static List<T_gonglv_account> Listdata_gl = new List<T_gonglv_account>();
  39. public static List<T_quekou_account> Listdata_qk = new List<T_quekou_account>();
  40. public static List<T_quxian_account> Listdata_qx_ = new List<T_quxian_account>(); //临时
  41. public static List<T_daocha_account> Listdata_dc_ = new List<T_daocha_account>(); //临时
  42. public static List<T_guanjie_account> Listdata_gj_ = new List<T_guanjie_account>(); //临时
  43. //获取局名信息
  44. public static List<string> Qxjm_List = new List<string>();
  45. public static List<string> Dcjm_List = new List<string>();
  46. public static List<string> Gjjm_List = new List<string>();
  47. public static void initList()
  48. {
  49. Listdata_qx.Clear();
  50. Listdata_dc.Clear();
  51. Listdata_gj.Clear();
  52. dataError.Clear();
  53. }
  54. /// <summary>
  55. /// 导入数据公共函数
  56. /// </summary>
  57. /// <param name="tablename">数据类型名称</param>
  58. public static bool GetTabledata(TableName tablename)
  59. {
  60. //DataSet ds = new DataSet();//新建数据集
  61. dataSsccess.Clear();
  62. OpenFileDialog fd = new OpenFileDialog();//首先根据打开文件对话框,选择excel表格
  63. fd.Multiselect = true;
  64. fd.Filter = "表格(*.xls,*.xlsx)| *.xls;*.xlsx|所有文件(*.*)|*.*";//打开文件对话框筛选器
  65. //fd.Filter = "xls文件(*.xls)|*.xls|xlsx文件(*.xlsx)|*.xlsx|所有文件(*.*)|*.*";//打开文件对话框筛选器
  66. string[] filenames;//文件完整的路径名
  67. if (fd.ShowDialog() == DialogResult.OK)
  68. {
  69. dataError.Add(new catchExcelError() { message = "test" });
  70. filenames = fd.FileNames;
  71. foreach (var strPath in filenames)
  72. {
  73. initList();
  74. string path = strPath;
  75. try
  76. {
  77. if (Path.GetExtension(strPath) == ".xls")
  78. {
  79. path = Application.StartupPath + "//result//temptz.xlsx";
  80. if (File.Exists(path))
  81. {
  82. File.Delete(path);
  83. }
  84. NPOIExt.ConvertToXlsx(strPath, path);
  85. }
  86. }
  87. catch (Exception)
  88. {
  89. XtraMessageBox.Show("文件"+ Path.GetFileName(strPath) + "损坏!请检查", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
  90. continue;
  91. }
  92. try
  93. {
  94. #region lpy's
  95. // /*OleDbConnection Con;
  96. //string strExtension = System.IO.Path.GetExtension(strPath);
  97. //switch (strExtension)
  98. //{
  99. // case ".xls":
  100. // Con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strPath + ";" + "Extended Properties=\"Excel 8.0;HDR=yes;IMEX=1;\"");
  101. // break;
  102. // case ".xlsx":
  103. // Con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + strPath + ";" + "Extended Properties=\"Excel 12.0;HDR=yes;IMEX=1;\"");//此连接可以操作.xls与.xlsx文件 (支持Excel2003 和 Excel2007 的连接字符串) 备注: "HDR=yes;"是说Excel文件的第一行是列名而不是数,"HDR=No;"正好与前面的相反。"IMEX=1 "如果列中的数据类型不一致,使用"IMEX=1"可必免数据类型冲突。
  104. // break;
  105. // default:
  106. // Con = null;
  107. // break;
  108. //}*/
  109. // //64
  110. // string strCon = "provider=Microsoft.ACE.OLEDB.12.0;data source=" + strPath + ";extended properties=excel 8.0";//关键是红色区域
  111. // //32
  112. // //string strCon = "provider=microsoft.jet.oledb.4.0;data source=" + strPath + ";extended properties=excel 8.0";//关键是红色区域
  113. // OleDbConnection Con = new OleDbConnection(strCon);//建立连接
  114. // string strSql = "select * from [Sheet1$]";//表名的写法也应注意不同,对应的excel表为sheet1,在这里要在其后加美元符号$,并用中括号
  115. // OleDbCommand Cmd = new OleDbCommand(strSql, Con);//建立要执行的命令
  116. // OleDbDataAdapter da = new OleDbDataAdapter(Cmd);//建立数据适配器
  117. // DataSet Table_data = new DataSet();
  118. // da.Fill(Table_data, "datatable");//把数据适配器中的数据读到数据集中的一个表中(此处表名为datatable,可以任取表名)
  119. // //指定datagridview1的数据源为数据集ds的第一张表(也就是shyman表),也可以写ds.Table["shyman"]
  120. #endregion
  121. List<List<string>> exceldata;
  122. switch (tablename)
  123. {
  124. case TableName.QX_Data:
  125. #region 读excel
  126. Listdata_qx_.Clear();
  127. try
  128. {
  129. exceldata = readExcel(path, 16);
  130. }
  131. catch
  132. {
  133. XtraMessageBox.Show("读取文件:“" + Path.GetFileName(strPath) + "”失败,怀疑文件已损坏!请检查", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
  134. continue;
  135. }
  136. for (int i = 0; i < exceldata.Count; i++)
  137. {
  138. T_quxian_account onescvdata = new T_quxian_account();
  139. int ii = 0;
  140. Type t = onescvdata.GetType();//获得该类的Type
  141. foreach (PropertyInfo pi in t.GetProperties())
  142. {
  143. catchExcelError EE = new catchExcelError();
  144. EE.row = i + 2;
  145. EE.column = ii;
  146. EE.message = ErrorM[0];
  147. string tt = pi.PropertyType.Name;
  148. if (pi.Name != "Id" && ii != exceldata[i].Count)
  149. {
  150. if (pi.Name == "Xianming" || pi.Name == "Hangbie" || pi.Name == "Qxfx")
  151. {
  152. if (exceldata[i][ii] == "")
  153. {
  154. dataError.Add(EE);
  155. ii++;
  156. continue;
  157. }
  158. pi.SetValue(onescvdata, exceldata[i][ii]);
  159. }
  160. else if (pi.Name == "Qzlc" || pi.Name == "Jslc" || pi.Name == "Qhhxc" || pi.Name == "Zhhxc" || pi.Name == "Chaogao")
  161. {
  162. if (exceldata[i][ii] == "")
  163. {
  164. dataError.Add(EE);
  165. ii++;
  166. continue;
  167. }
  168. if (pi.Name == "Qzlc" && (exceldata[i][ii].Contains('(') || exceldata[i][ii].Contains('-')))
  169. {
  170. ii++;
  171. pi.SetValue(onescvdata, Convert.ToDecimal(0));
  172. continue;
  173. }
  174. try
  175. {
  176. pi.SetValue(onescvdata, Convert.ToDecimal(exceldata[i][ii]));
  177. }
  178. catch
  179. {
  180. EE.message = ErrorM[1];
  181. dataError.Add(EE);
  182. }
  183. }
  184. else
  185. {
  186. if (tt == "String")
  187. {
  188. pi.SetValue(onescvdata, exceldata[i][ii]);
  189. }
  190. else
  191. {
  192. string cha = exceldata[i][ii].Replace("(", "-");
  193. cha = cha.Replace("(", "-");
  194. cha = cha.Replace(")", "");
  195. cha = cha.Replace(")", "");
  196. try
  197. {
  198. pi.SetValue(onescvdata, Convert.ToDecimal(cha));
  199. }
  200. catch
  201. {
  202. EE.message = ErrorM[1];
  203. dataError.Add(EE);
  204. }
  205. }
  206. }
  207. ii++;
  208. }
  209. }
  210. Listdata_qx_.Add(onescvdata);
  211. }
  212. if (dataError.Count == 0)
  213. {
  214. Listdata_qx = Listdata_qx.Concat(Listdata_qx_).ToList();
  215. }
  216. #endregion
  217. //Listdata_qx = DataTableToList<T_quxian_account>(Table_data.Tables[0], TableName.QX_Data);
  218. ////生成唯一编码id
  219. //foreach (var item in Listdata_qx)
  220. //{
  221. // string uuid = System.Guid.NewGuid().ToString("N");
  222. // item.Id = uuid;
  223. //}
  224. break;
  225. case TableName.DC_Data:
  226. #region 读excel
  227. Listdata_dc_.Clear();
  228. try
  229. {
  230. exceldata = readExcel(path, 18);
  231. }
  232. catch
  233. {
  234. XtraMessageBox.Show("读取文件:“" + Path.GetFileName(strPath) + "”失败,怀疑文件已损坏!请检查", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
  235. continue;
  236. }
  237. for (int i = 0; i < exceldata.Count; i++)
  238. {
  239. T_daocha_account onescvdata = new T_daocha_account();
  240. int ii = 0;
  241. Type t = onescvdata.GetType();//获得该类的Type
  242. foreach (PropertyInfo pi in t.GetProperties())
  243. {
  244. catchExcelError EE = new catchExcelError();
  245. EE.row = i + 2;
  246. EE.column = ii;
  247. EE.message = ErrorM[0];
  248. string tt = pi.PropertyType.Name;
  249. if (pi.Name != "Id" && ii != exceldata[i].Count)
  250. {
  251. if (pi.Name == "Xlm" || pi.Name == "Xingbie" || pi.Name == "Czm" || pi.Name == "Dcbh")
  252. {
  253. if (exceldata[i][ii] == "")
  254. {
  255. dataError.Add(EE);
  256. ii++;
  257. continue;
  258. }
  259. pi.SetValue(onescvdata, exceldata[i][ii]);
  260. }
  261. else if (pi.Name == "Jgjlc" || pi.Name == "Zch" || pi.Name == "Quanchang")
  262. {
  263. if (exceldata[i][ii] == "")
  264. {
  265. dataError.Add(EE);
  266. ii++;
  267. continue;
  268. }
  269. string cha = exceldata[i][ii].Replace("(", "-");
  270. cha = cha.Replace("(", "-");
  271. cha = cha.Replace(")", "");
  272. cha = cha.Replace(")", "");
  273. try
  274. {
  275. pi.SetValue(onescvdata, Convert.ToDecimal(cha));
  276. }
  277. catch
  278. {
  279. EE.message = ErrorM[1];
  280. dataError.Add(EE);
  281. }
  282. }
  283. else
  284. {
  285. if (tt == "String")
  286. {
  287. pi.SetValue(onescvdata, exceldata[i][ii]);
  288. }
  289. else
  290. {
  291. string cha = exceldata[i][ii].Replace("(", "-");
  292. cha = cha.Replace("(", "-");
  293. cha = cha.Replace(")", "");
  294. cha = cha.Replace(")", "");
  295. try
  296. {
  297. pi.SetValue(onescvdata, Convert.ToDecimal(cha));
  298. }
  299. catch
  300. {
  301. EE.message = ErrorM[1];
  302. dataError.Add(EE);
  303. }
  304. }
  305. }
  306. ii++;
  307. }
  308. }
  309. Listdata_dc_.Add(onescvdata);
  310. }
  311. if (dataError.Count == 0)
  312. {
  313. Listdata_dc = Listdata_dc.Concat(Listdata_dc_).ToList();
  314. }
  315. #endregion
  316. break;
  317. case TableName.GJ_Data:
  318. #region 读excel
  319. Listdata_gj_.Clear();
  320. try
  321. {
  322. exceldata = readExcel(path, 6);
  323. }
  324. catch
  325. {
  326. XtraMessageBox.Show("读取文件:“" + Path.GetFileName(strPath) + "”失败,怀疑文件已损坏!请检查", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
  327. continue;
  328. }
  329. for (int i = 0; i < exceldata.Count; i++)
  330. {
  331. T_guanjie_account onescvdata = new T_guanjie_account();
  332. int ii = 0;
  333. Type t = onescvdata.GetType();//获得该类的Type
  334. foreach (PropertyInfo pi in t.GetProperties())
  335. {
  336. catchExcelError EE = new catchExcelError();
  337. EE.row = i + 2;
  338. EE.column = ii ;
  339. EE.message = ErrorM[0];
  340. string tt = pi.PropertyType.Name;
  341. if (pi.Name != "Id" && ii != exceldata[i].Count)
  342. {
  343. if (exceldata[i][ii] == "")
  344. {
  345. dataError.Add(EE);
  346. ii++;
  347. continue;
  348. }
  349. if (tt == "String")
  350. {
  351. pi.SetValue(onescvdata, exceldata[i][ii]);
  352. }
  353. else
  354. {
  355. string cha = exceldata[i][ii].Replace("(", "-");
  356. cha = cha.Replace("(", "-");
  357. cha = cha.Replace(")", "");
  358. cha = cha.Replace(")", "");
  359. try
  360. {
  361. pi.SetValue(onescvdata, Convert.ToDecimal(cha));
  362. }
  363. catch
  364. {
  365. EE.message = ErrorM[1];
  366. dataError.Add(EE);
  367. }
  368. }
  369. ii++;
  370. }
  371. }
  372. Listdata_gj_.Add(onescvdata);
  373. }
  374. if (dataError.Count == 0)
  375. {
  376. Listdata_gj = Listdata_gj.Concat(Listdata_gj_).ToList();
  377. }
  378. #endregion
  379. break;
  380. default: break;
  381. }
  382. }
  383. catch (Exception ex)
  384. {
  385. XtraMessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);//捕捉异常
  386. }
  387. if (dataError.Count != 0)
  388. {
  389. string mess = "文件:" + Path.GetFileName(strPath) + "终止导入!\r\n";
  390. foreach (var item in dataError)
  391. {
  392. mess += "第“" + item.row + "”行,第“" + GetColumnChar(item.column) + "”列数据导入错误:" + item.message + "\r\n";
  393. }
  394. XtraMessageBox.Show(mess, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
  395. }
  396. else if(!(dataError.Count == 1 && dataError[0].message == "test"))
  397. {
  398. dataSsccess.Add("文件:" + Path.GetFileName(strPath) + "导入成功!");
  399. }
  400. }
  401. return true;
  402. }
  403. return false;
  404. }
  405. private static List<List<string>> readExcel(string path,int cellcount)
  406. {
  407. List<List<string>> datares = new List<List<string>>();
  408. var workbook = new XLWorkbook(path);
  409. IXLWorksheet XLWorksheet = workbook.Worksheet(1);
  410. int rowcount = XLWorksheet.RowCount();
  411. for (int i = 2; i <= rowcount; i++)
  412. {
  413. if (XLWorksheet.Row(i).Cell(1).IsEmpty())
  414. {
  415. break;
  416. }
  417. List<string> cellres = new List<string>();
  418. for (int j = 1; j <= cellcount; j++)
  419. {
  420. //获得单元格
  421. var cell = XLWorksheet.Row(i).Cell(j);
  422. cellres.Add(cell.Value.ToString());
  423. }
  424. datares.Add(cellres);
  425. }
  426. return datares;
  427. }
  428. /// <summary>
  429. /// datatable转成实体类
  430. /// </summary>
  431. /// <typeparam name="T">实体类</typeparam>
  432. /// <param name="dt">datatable数据</param>
  433. /// <returns></returns>
  434. private static List<T> DataTableToList<T>(DataTable dt, TableName tablename) where T : class, new()
  435. {
  436. Assist_quxian assist_quxian = new Assist_quxian();
  437. Assist_daocha assist_daocha = new Assist_daocha();
  438. Assist_guanjie assist_guanjie = new Assist_guanjie();
  439. if (dt == null || dt.Rows.Count == 0)
  440. return null;
  441. List<T> result = new List<T>();
  442. foreach (DataRow dr in dt.Rows)
  443. {
  444. try
  445. {
  446. T res = new T();
  447. for (int i = 0; i < dr.Table.Columns.Count; i++)
  448. {
  449. PropertyInfo propertyInfo = null;
  450. switch (tablename)
  451. {
  452. case TableName.QX_Data:
  453. propertyInfo = res.GetType().GetProperty(GetTypeValue(dr.Table.Columns[i].ColumnName, assist_quxian), BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
  454. break;
  455. case TableName.DC_Data:
  456. propertyInfo = res.GetType().GetProperty(GetTypeValue(dr.Table.Columns[i].ColumnName, assist_daocha), BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
  457. break;
  458. case TableName.GJ_Data:
  459. propertyInfo = res.GetType().GetProperty(GetTypeValue(dr.Table.Columns[i].ColumnName, assist_guanjie), BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
  460. break;
  461. default: break;
  462. }
  463. if (propertyInfo != null)
  464. {
  465. var value = dr[i];
  466. switch (propertyInfo.PropertyType.FullName)
  467. {
  468. case "System.Decimal":
  469. if (value == DBNull.Value) { propertyInfo.SetValue(res, 0.0, null); break; }
  470. propertyInfo.SetValue(res, Convert.ToDecimal(value), null); break;
  471. case "System.String":
  472. if (value == DBNull.Value) { propertyInfo.SetValue(res, "-", null); break; }
  473. propertyInfo.SetValue(res, value.ToString(), null); break;
  474. case "System.Int32":
  475. if (value == DBNull.Value) { propertyInfo.SetValue(res, 0, null); break; }
  476. propertyInfo.SetValue(res, Convert.ToInt32(value), null); break;
  477. case "System.Double":
  478. if (value == DBNull.Value) { propertyInfo.SetValue(res, 0.0, null); break; }
  479. propertyInfo.SetValue(res, Convert.ToDouble(value), null); break;
  480. default:
  481. propertyInfo.SetValue(res, value, null); break;
  482. }
  483. }
  484. }
  485. result.Add(res);
  486. }
  487. catch (Exception ex)
  488. {
  489. ex = new Exception(string.Format("请检查第{0}行数据",result.Count+2));
  490. throw ex;
  491. }
  492. }
  493. return result;
  494. }
  495. /// <summary>
  496. /// 辅助类转化器
  497. /// </summary>
  498. /// <typeparam name="T">类</typeparam>
  499. /// <param name="s">属性值</param>
  500. /// <param name="t">实例化类</param>
  501. /// <returns></returns>
  502. private static string GetTypeValue<T>(string s, T t)
  503. {
  504. string columnName = "";
  505. Type assistType = t.GetType();
  506. PropertyInfo[] properties = typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);
  507. for (int i = 0; i < assistType.GetFields().Length; i++)
  508. {
  509. if (assistType.GetFields()[i] != null)
  510. {
  511. if (assistType.GetFields()[i].GetValue(t) != null && assistType.GetFields()[i].GetValue(t).ToString() == s)
  512. {
  513. columnName = assistType.GetFields()[i].Name;
  514. //Debug.LogError(assistType.GetFields()[i].Name);
  515. break;
  516. }
  517. }
  518. }
  519. return columnName;
  520. }
  521. /// <summary>
  522. /// excel列数转为字母列号
  523. /// </summary>
  524. /// <param name="col"></param>
  525. /// <returns></returns>
  526. private static string GetColumnChar(int col)
  527. {
  528. var a = col / 26;
  529. var b = col % 26;
  530. if (a > 0) return GetColumnChar(a - 1) + (char)(b + 65);
  531. return ((char)(b + 65)).ToString();
  532. }
  533. }
  534. }