TZCommonFunc.cs 30 KB

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