DataTableEx.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  1. using System;
  2. using System.Data;
  3. using System.IO;
  4. using System.Runtime.Serialization;
  5. using System.Runtime.Serialization.Formatters.Binary;
  6. using System.Collections.Generic;
  7. namespace ZcPeng.PublicLibrary
  8. {
  9. /// <summary>
  10. /// DataTableEx
  11. /// 功能:操作DataTable的一些静态方法。
  12. /// 作者:彭昭成
  13. /// 时间:2018年12月10日
  14. /// </summary>
  15. public static class DataTableEx
  16. {
  17. /// <summary>
  18. /// 将DataTable序列化成字节数组
  19. /// </summary>
  20. /// <param name="dt">数据表</param>
  21. /// <returns>如果序列化成功,返回字节数组;否则返回null。</returns>
  22. public static byte[] Serialize(DataTable dt)
  23. {
  24. byte[] bytes = null;
  25. if (dt != null)
  26. {
  27. MemoryStream ms = new MemoryStream();
  28. BinaryFormatter bf = new BinaryFormatter();
  29. try
  30. {
  31. bf.Serialize(ms, dt);
  32. bytes = ms.ToArray();
  33. }
  34. catch { }
  35. ms.Close();
  36. }
  37. return bytes;
  38. }
  39. /// <summary>
  40. /// 将字节数组反序列化为DataTable对象
  41. /// </summary>
  42. /// <param name="bytes">字节数组</param>
  43. /// <returns>返回数据表;如果失败,返回null。</returns>
  44. public static DataTable Deserialize(byte[] bytes)
  45. {
  46. DataTable dt = null;
  47. if (bytes != null && bytes.Length > 0)
  48. {
  49. BinaryFormatter bf = new BinaryFormatter();
  50. MemoryStream ms = new MemoryStream(bytes);
  51. try
  52. {
  53. dt = (DataTable)bf.Deserialize(ms);
  54. }
  55. catch { }
  56. ms.Close();
  57. }
  58. return dt;
  59. }
  60. /// <summary>
  61. /// 从数据表中移除列名列表中的列
  62. /// </summary>
  63. /// <param name="dt">数据表</param>
  64. /// <param name="columnList">需要被移除的列名列表</param>
  65. /// <returns>返回成功移除列的数目</returns>
  66. public static int RemoveDataColumn(DataTable dt, List<string> columnList)
  67. {
  68. int count = 0;
  69. if (dt != null && dt.Columns != null && dt.Columns.Count > 0 && columnList != null && columnList.Count > 0)
  70. {
  71. foreach (string columnName in columnList)
  72. {
  73. if (dt.Columns.Contains(columnName))
  74. {
  75. DataColumn dc = dt.Columns[columnName];
  76. if (dt.Columns.CanRemove(dc))
  77. {
  78. dt.Columns.Remove(dc);
  79. count++;
  80. }
  81. }
  82. }
  83. }
  84. return count;
  85. }
  86. /// <summary>
  87. /// 从数据表中移除列名列表中的列
  88. /// </summary>
  89. /// <param name="dt">数据表</param>
  90. /// <param name="columnList">需要被移除的列名列表</param>
  91. /// <returns>返回成功移除列的数目</returns>
  92. public static int RemoveDataColumn(DataTable dt, string[] columnList)
  93. {
  94. if (columnList.Length > 0)
  95. return RemoveDataColumn(dt, new List<string>(columnList));
  96. else
  97. return 0;
  98. }
  99. /// <summary>
  100. /// 比较两个数据表的表结构是否相同;
  101. /// 比较过程如下:
  102. /// (1)比较列数目是否相同;
  103. /// (2)比较每列的列名及数据类型是否相同。
  104. /// </summary>
  105. /// <param name="dt1">数据表1</param>
  106. /// <param name="dt2">数据表2</param>
  107. /// <param name="needSameColumnOrder">是否需要列的次序保持一致</param>
  108. /// <returns>返回比较的结果。</returns>
  109. public static bool CompareTableStructure(DataTable dt1, DataTable dt2, bool needSameColumnOrder)
  110. {
  111. if (dt1 == null && dt2 == null)
  112. return true;
  113. if ((dt1 == null && dt2 != null) || (dt1 != null && dt2 == null))
  114. return false;
  115. if (dt1 != null && dt2 != null)
  116. {
  117. if (dt1.Columns.Count != dt2.Columns.Count) //列数目不同
  118. return false;
  119. for (int i = 0; i < dt1.Columns.Count; i++)
  120. {
  121. if (needSameColumnOrder)
  122. {
  123. if (dt1.Columns[i].ColumnName != dt2.Columns[i].ColumnName || dt1.Columns[i].DataType != dt2.Columns[i].DataType) //列名或者列数据类型不一致
  124. return false;
  125. }
  126. else
  127. {
  128. DataColumn dc = dt1.Columns[i];
  129. if (!dt2.Columns.Contains(dc.ColumnName)) //数据表2中不包含数据表1中的某列
  130. return false;
  131. if (dc.DataType != dt2.Columns[dc.ColumnName].DataType) //列的数据类型不同
  132. return false;
  133. }
  134. }
  135. }
  136. return true;
  137. }
  138. /// <summary>
  139. /// 合并数据表:将dtSource表中的数据行添加到dtDest表的行之后
  140. /// </summary>
  141. /// <param name="dtDest">目标数据表</param>
  142. /// <param name="dtSource">源数据表</param>
  143. /// <returns>返回是否合并成功。</returns>
  144. public static bool Merge(ref DataTable dtDest, DataTable dtSource)
  145. {
  146. if (dtSource == null || dtSource.Rows == null || dtSource.Rows.Count == 0)
  147. return false;
  148. if (dtDest == null)
  149. dtDest = dtSource.Copy();
  150. else
  151. {
  152. if (!CompareTableStructure(dtDest, dtSource, false)) //如果表结构不一致,返回
  153. return false;
  154. foreach (DataRow drSource in dtSource.Rows)
  155. {
  156. DataRow drNew = dtDest.NewRow();
  157. for (int i = 0; i < dtDest.Columns.Count; i++)
  158. drNew[i] = drSource[dtDest.Columns[i].ColumnName]; //drNew[i] = drSource[i];
  159. dtDest.Rows.Add(drNew);
  160. }
  161. }
  162. dtDest.AcceptChanges();
  163. return true;
  164. }
  165. /// <summary>
  166. /// 从指定数据表中查找特定值所在的数据行
  167. /// </summary>
  168. /// <param name="dt">数据表</param>
  169. /// <param name="columnName">被查找的列名</param>
  170. /// <param name="value">被查找的值</param>
  171. /// <returns>如果成功找到了值所在的数据行,返回数据行;否则返回null。</returns>
  172. public static DataRow FindDataRow(DataTable dt, string columnName, object value)
  173. {
  174. if (dt != null)
  175. {
  176. int columnIndex = dt.Columns.IndexOf(columnName);
  177. return FindDataRow(dt, columnIndex, value);
  178. }
  179. else
  180. return null;
  181. }
  182. /// <summary>
  183. /// 从指定数据表中查找特定值所在的数据行
  184. /// </summary>
  185. /// <param name="dt">数据表</param>
  186. /// <param name="columnName">被查找的列名</param>
  187. /// <param name="value">被查找的值</param>
  188. /// <returns>如果成功找到了值所在的数据行,返回数据行的索引;否则返回-1。</returns>
  189. public static int FindDataRowIndex(DataTable dt, string columnName, object value)
  190. {
  191. if (dt != null)
  192. {
  193. int columnIndex = dt.Columns.IndexOf(columnName);
  194. return FindDataRowIndex(dt, columnIndex, value);
  195. }
  196. else
  197. return -1;
  198. }
  199. /// <summary>
  200. /// 从指定数据表中查找特定值所在的数据行
  201. /// </summary>
  202. /// <param name="dt">数据表</param>
  203. /// <param name="columnIndex">被查找的列索引</param>
  204. /// <param name="value">被查找的值</param>
  205. /// <returns>如果成功找到了值所在的数据行,返回数据行;否则返回null。</returns>
  206. public static DataRow FindDataRow(DataTable dt, int columnIndex, object value)
  207. {
  208. int rowIndex = FindDataRowIndex(dt, columnIndex, value);
  209. if (rowIndex != -1)
  210. return dt.Rows[rowIndex];
  211. else
  212. return null;
  213. }
  214. /// <summary>
  215. /// 从指定数据表中查找特定值所在的数据行
  216. /// </summary>
  217. /// <param name="dt">数据表</param>
  218. /// <param name="columnIndex">被查找的列索引</param>
  219. /// <param name="value">被查找的值</param>
  220. /// <returns>如果成功找到了值所在的数据行,返回数据行的索引;否则返回-1。</returns>
  221. public static int FindDataRowIndex(DataTable dt, int columnIndex, object value)
  222. {
  223. int rowIndex = -1;
  224. if (dt != null && dt.Rows != null && dt.Rows.Count > 0 && columnIndex >= 0 && columnIndex < dt.Columns.Count)
  225. {
  226. Type type = value.GetType();
  227. if (dt.Columns[columnIndex].DataType == type)
  228. {
  229. if (type.IsValueType || type == typeof(string))
  230. {
  231. for (int i = 0; i < dt.Rows.Count; i++)
  232. {
  233. if (dt.Rows[i][columnIndex].ToString() == value.ToString())
  234. {
  235. rowIndex = i;
  236. break;
  237. }
  238. }
  239. }
  240. else
  241. {
  242. for (int i = 0; i < dt.Rows.Count; i++)
  243. {
  244. if (dt.Rows[i][columnIndex] == value)
  245. {
  246. rowIndex = i;
  247. break;
  248. }
  249. }
  250. }
  251. }
  252. }
  253. return rowIndex;
  254. }
  255. /// <summary>
  256. /// 从指定数据表中查找特定值所在的数据行
  257. /// </summary>
  258. /// <param name="dt">数据表</param>
  259. /// <param name="columnNameAndValues">关键列及值</param>
  260. /// <returns>如果成功找到了值所在的数据行,返回数据行;否则返回null。</returns>
  261. public static DataRow FindDataRow(DataTable dt, Dictionary<int, object> columnIndexAndValues)
  262. {
  263. int rowIndex = FindDataRowIndex(dt, columnIndexAndValues);
  264. if (rowIndex != -1)
  265. return dt.Rows[rowIndex];
  266. else
  267. return null;
  268. }
  269. /// <summary>
  270. /// 从指定数据表中查找特定值所在的数据行
  271. /// </summary>
  272. /// <param name="dt">数据表</param>
  273. /// <param name="columnIndexAndValues">关键列及值</param>
  274. /// <returns>如果成功找到了值所在的数据行,返回数据行的索引;否则返回-1。</returns>
  275. public static int FindDataRowIndex(DataTable dt, Dictionary<int, object> columnIndexAndValues)
  276. {
  277. int rowIndex = -1;
  278. if (dt != null && dt.Rows != null && dt.Rows.Count > 0)
  279. {
  280. //检查关键列是否都有效
  281. int columnCount = dt.Columns.Count;
  282. foreach (KeyValuePair<int, object> pair in columnIndexAndValues)
  283. {
  284. if (pair.Key < 0 || pair.Key >= columnCount) //索引是否在范围内
  285. return -1;
  286. if (dt.Columns[pair.Key].DataType != pair.Value.GetType()) //类型是否相同
  287. return -1;
  288. }
  289. //依次在每行中查找
  290. for (int i = 0; i < dt.Rows.Count; i++)
  291. {
  292. bool match = true;
  293. DataRow dr = dt.Rows[i];
  294. foreach (KeyValuePair<int, object> pair in columnIndexAndValues)
  295. {
  296. Type type = pair.Value.GetType();
  297. if (type.IsValueType || type == typeof(string))
  298. {
  299. if (dr[pair.Key].ToString() != pair.Value.ToString())
  300. {
  301. match = false;
  302. break;
  303. }
  304. }
  305. else
  306. {
  307. if (dr[pair.Key] != pair.Value)
  308. {
  309. match = false;
  310. break;
  311. }
  312. }
  313. }
  314. if (match)
  315. {
  316. rowIndex = i;
  317. break;
  318. }
  319. }
  320. }
  321. return rowIndex;
  322. }
  323. /// <summary>
  324. /// 从指定数据表中查找特定值所在的数据行
  325. /// </summary>
  326. /// <param name="dt">数据表</param>
  327. /// <param name="columnNameAndValues">关键列及值</param>
  328. /// <returns>如果成功找到了值所在的数据行,返回数据行;否则返回null。</returns>
  329. public static DataRow FindDataRow(DataTable dt, Dictionary<string, object> columnNameAndValues)
  330. {
  331. int rowIndex = FindDataRowIndex(dt, columnNameAndValues);
  332. if (rowIndex != -1)
  333. return dt.Rows[rowIndex];
  334. else
  335. return null;
  336. }
  337. /// <summary>
  338. /// 从指定数据表中查找特定值所在的数据行
  339. /// </summary>
  340. /// <param name="dt">数据表</param>
  341. /// <param name="columnIndexAndValues">关键列及值</param>
  342. /// <returns>如果成功找到了值所在的数据行,返回数据行的索引;否则返回-1。</returns>
  343. public static int FindDataRowIndex(DataTable dt, Dictionary<string, object> columnNameAndValues)
  344. {
  345. if (dt == null || dt.Rows == null || dt.Rows.Count == 0)
  346. return -1;
  347. //先将关键列名转换成列号,然后再查找
  348. Dictionary<int, object> columnIndexAndValues = new Dictionary<int, object>(columnNameAndValues.Count);
  349. foreach (KeyValuePair<string, object> pair in columnNameAndValues)
  350. {
  351. int columnIndex = dt.Columns.IndexOf(pair.Key);
  352. if (columnIndex >= 0)
  353. columnIndexAndValues.Add(columnIndex, pair.Value);
  354. else
  355. return -1;
  356. }
  357. return FindDataRowIndex(dt, columnIndexAndValues);
  358. }
  359. /// <summary>
  360. /// 汇总数据表:对于dtSource与dtDest共有的数据行,将dtSource表中的数据累加到dtDest表;对于dtSource中多出的数据行,添加到dtDest表之中;对于dtDest中多出的数据行,保持原样。
  361. /// 注:要求dtDest和dtSource有相同的表结构,并且除了关键列之外的其他列数据类型均为整型。
  362. /// </summary>
  363. /// <param name="dtDest">目标数据表</param>
  364. /// <param name="dtSource">源数据表</param>
  365. /// <param name="keyColumnName">关键列名</param>
  366. /// <returns>返回是否汇总成功。</returns>
  367. public static bool Summarize(ref DataTable dtDest, DataTable dtSource, string keyColumnName)
  368. {
  369. if (dtSource == null || dtSource.Rows == null || dtSource.Rows.Count == 0)
  370. return false;
  371. if (dtDest == null)
  372. dtDest = dtSource.Copy();
  373. else
  374. {
  375. if (!CompareTableStructure(dtDest, dtSource, false)) //如果表结构不一致,返回
  376. return false;
  377. if (!dtDest.Columns.Contains(keyColumnName)) //如果表中不包含关键列,返回
  378. return false;
  379. foreach (DataRow drSource in dtSource.Rows)
  380. {
  381. DataRow drDest = FindDataRow(dtDest, keyColumnName, drSource[keyColumnName]);
  382. if (drDest != null)
  383. {
  384. //如果在dtDest中找到了数据行,累加数据
  385. for (int i = 0; i < dtDest.Columns.Count; i++)
  386. {
  387. string columnName = dtDest.Columns[i].ColumnName;
  388. if (columnName != keyColumnName)
  389. drDest[i] = (Convert.IsDBNull(drDest[i]) ? 0 : (int)drDest[i]) + (Convert.IsDBNull(drSource[columnName]) ? 0 : (int)drSource[columnName]);
  390. }
  391. }
  392. else
  393. {
  394. //如果没有找到区域对应的行,创建新行
  395. DataRow drNew = dtDest.NewRow();
  396. for (int i = 0; i < dtDest.Columns.Count; i++)
  397. {
  398. string columnName = dtDest.Columns[i].ColumnName;
  399. drNew[i] = drSource[columnName];
  400. }
  401. dtDest.Rows.Add(drNew);
  402. }
  403. }
  404. }
  405. dtDest.AcceptChanges();
  406. return true;
  407. }
  408. /// <summary>
  409. /// 汇总数据表:对于dtSource与dtDest共有的数据行,将dtSource表中的数据累加到dtDest表;对于dtSource中多出的数据行,添加到dtDest表之中;对于dtDest中多出的数据行,保持原样。
  410. /// </summary>
  411. /// <param name="dtDest">目标数据表</param>
  412. /// <param name="dtSource">源数据表</param>
  413. /// <param name="keyColumnIndex">关键列索引</param>
  414. /// <returns>返回是否汇总成功。</returns>
  415. public static bool Summarize(ref DataTable dtDest, DataTable dtSource, int keyColumnIndex)
  416. {
  417. if (dtSource != null && keyColumnIndex >= 0 && keyColumnIndex < dtSource.Columns.Count)
  418. {
  419. string keyColumnName = dtSource.Columns[keyColumnIndex].ColumnName;
  420. return Summarize(ref dtDest, dtSource, keyColumnName);
  421. }
  422. else
  423. return false;
  424. }
  425. /// <summary>
  426. /// 汇总数据表:对于dtSource与dtDest共有的数据行,将dtSource表中的数据累加到dtDest表;对于dtSource中多出的数据行,添加到dtDest表之中;对于dtDest中多出的数据行,保持原样。
  427. /// 注:要求dtDest和dtSource有相同的表结构,并且除了关键列之外的其他列数据类型均为整型。
  428. /// </summary>
  429. /// <param name="dtDest">目标数据表</param>
  430. /// <param name="dtSource">源数据表</param>
  431. /// <param name="keyColumnName">关键列名</param>
  432. /// <returns>返回是否汇总成功。</returns>
  433. public static bool Summarize(ref DataTable dtDest, DataTable dtSource, List<string> keyColumnNames)
  434. {
  435. if (dtSource == null || dtSource.Rows == null || dtSource.Rows.Count == 0)
  436. return false;
  437. if (dtDest == null)
  438. dtDest = dtSource.Copy();
  439. else
  440. {
  441. if (!CompareTableStructure(dtDest, dtSource, false)) //如果表结构不一致,返回
  442. return false;
  443. foreach (string keyColumnName in keyColumnNames)
  444. {
  445. if (!dtDest.Columns.Contains(keyColumnName)) //如果表中不包含关键列,返回
  446. return false;
  447. }
  448. foreach (DataRow drSource in dtSource.Rows)
  449. {
  450. //查找关键列在源表中的值
  451. Dictionary<string, object> columnNameAndValues = new Dictionary<string, object>();
  452. foreach (string keyColumnName in keyColumnNames)
  453. columnNameAndValues.Add(keyColumnName, drSource[keyColumnName]);
  454. //在目标表中查找匹配的数据行
  455. DataRow drDest = FindDataRow(dtDest, columnNameAndValues);
  456. if (drDest != null)
  457. {
  458. //如果在dtDest中找到了数据行,累加数据
  459. for (int i = 0; i < dtDest.Columns.Count; i++)
  460. {
  461. string columnName = dtDest.Columns[i].ColumnName;
  462. if (!keyColumnNames.Contains(columnName))
  463. drDest[i] = (Convert.IsDBNull(drDest[i]) ? 0 : (int)drDest[i]) + (Convert.IsDBNull(drSource[columnName]) ? 0 : (int)drSource[columnName]);
  464. }
  465. }
  466. else
  467. {
  468. //如果没有找到区域对应的行,创建新行
  469. DataRow drNew = dtDest.NewRow();
  470. for (int i = 0; i < dtDest.Columns.Count; i++)
  471. {
  472. string columnName = dtDest.Columns[i].ColumnName;
  473. drNew[i] = drSource[columnName];
  474. }
  475. dtDest.Rows.Add(drNew);
  476. }
  477. }
  478. }
  479. dtDest.AcceptChanges();
  480. return true;
  481. }
  482. /// <summary>
  483. /// 汇总数据表:对于dtSource与dtDest共有的数据行,将dtSource表中的数据累加到dtDest表;对于dtSource中多出的数据行,添加到dtDest表之中;对于dtDest中多出的数据行,保持原样。
  484. /// </summary>
  485. /// <param name="dtDest">目标数据表</param>
  486. /// <param name="dtSource">源数据表</param>
  487. /// <param name="keyColumnIndex">关键列索引</param>
  488. /// <returns>返回是否汇总成功。</returns>
  489. public static bool Summarize(ref DataTable dtDest, DataTable dtSource, List<int> keyColumnIndexes)
  490. {
  491. if (dtSource != null)
  492. {
  493. List<string> keyColumnNames = new List<string>(keyColumnIndexes.Count);
  494. int columnCount = dtSource.Columns.Count;
  495. foreach (int keyColumnIndex in keyColumnIndexes)
  496. {
  497. if (keyColumnIndex >= 0 && keyColumnIndex < columnCount)
  498. keyColumnNames.Add(dtSource.Columns[keyColumnIndex].ColumnName);
  499. else
  500. return false;
  501. }
  502. return Summarize(ref dtDest, dtSource, keyColumnNames);
  503. }
  504. else
  505. return true;
  506. }
  507. }
  508. }