DataGridViewEx.cs 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Windows.Forms;
  5. using System.IO;
  6. using System.Drawing;
  7. using System.Drawing.Drawing2D;
  8. using System.ComponentModel;
  9. using System.Data;
  10. namespace LYFZ.ComponentLibrary
  11. {
  12. public class DataGridViewEx : System.Windows.Forms.DataGridView
  13. {
  14. /// <summary>
  15. /// 实现分页后
  16. /// </summary>
  17. public DataGridViewEx()
  18. : base()
  19. {
  20. try
  21. { RefreshTheme(); }
  22. catch { }
  23. this.Paint += DataGridViewEx_Paint;
  24. this.CellMouseDown += DataGridViewEx_CellMouseDown;
  25. this.CellPainting += DataGridViewEx_CellPainting;
  26. }
  27. /// <summary>
  28. /// 设置要隐藏的手机号字段名
  29. /// </summary>
  30. void SetHidePhoneCellsName()
  31. {
  32. if (this.Columns != null)
  33. {
  34. HidePhoneFindList.Clear();
  35. for (int i = 0; i < this.Columns.Count; i++)
  36. {
  37. DataGridViewColumn Column = this.Columns[i];
  38. if (_HidePhoneCellsNameList.Contains(Column.Name) || _HidePhoneCellsNameList.Contains(Column.HeaderText))
  39. {
  40. HidePhoneFindList.Add(Column.Name);
  41. }
  42. }
  43. }
  44. }
  45. // string[] HidePhoneFinds = "客户电话,电话,固定电话,介绍人电话,手机号码,本人手机,老公手机".Split(',');
  46. List<string> HidePhoneFindList = new List<string>();
  47. /// <summary>
  48. ///
  49. /// </summary>
  50. static List<string> _HidePhoneCellsNameList = new List<string>();//当前手机号字段列名
  51. /// <summary>
  52. /// 要将字段值显示为“*”号的字段列名(当前手机号字段列名)
  53. /// </summary>
  54. public static List<string> HidePhoneCellsNameList
  55. {
  56. get { return DataGridViewEx._HidePhoneCellsNameList; }
  57. }
  58. bool _EraseCell = false;
  59. /// <summary>
  60. /// 是否开启擦除单元格功能
  61. /// </summary>
  62. public bool EraseCell
  63. {
  64. get { return _EraseCell; }
  65. set { _EraseCell = value; }
  66. }
  67. public string EraseCellDrawLine
  68. {
  69. get { return "@EraseCellDrawLine@"; }
  70. }
  71. public string EraseCellDrawLineVEnd
  72. {
  73. get { return "@EraseCellDrawLine@VEnd"; }
  74. }
  75. public string EraseCellDrawLineHEnd
  76. {
  77. get { return "@EraseCellDrawLine@HEnd"; }
  78. }
  79. public string EraseCellDrawLineVHEnd
  80. {
  81. get { return "@EraseCellDrawLine@VHEnd"; }
  82. }
  83. /// <summary>
  84. /// 擦除单元格
  85. /// </summary>
  86. /// <param name="e"></param>
  87. void EraseCellPainting(DataGridViewCellPaintingEventArgs e)
  88. {
  89. if (EraseCell)
  90. {
  91. if (e.RowIndex < 0 || e.ColumnIndex < 0) { return; }
  92. Brush gridBrush = new SolidBrush(this.GridColor);
  93. SolidBrush backBrush = new SolidBrush(e.CellStyle.BackColor);
  94. object EraseCellValue = this.Rows[e.RowIndex].Cells[e.ColumnIndex].Tag;
  95. if (EraseCellValue != null && (EraseCellValue.ToString().ToLower().Contains(EraseCellDrawLine.ToLower())))
  96. {
  97. // cellwidth = e.CellBounds.Width;
  98. Pen gridLinePen = new Pen(gridBrush);
  99. if (this.Rows[e.RowIndex].Selected)
  100. {
  101. backBrush.Color = e.CellStyle.SelectionBackColor;
  102. }
  103. //以背景色填充
  104. e.Graphics.FillRectangle(backBrush, e.CellBounds);
  105. if (EraseCellValue.ToString().ToLower() == EraseCellDrawLineHEnd.ToLower() || EraseCellValue.ToString().ToLower() == EraseCellDrawLineVHEnd.ToLower())
  106. {
  107. //画下面的线
  108. e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left, e.CellBounds.Bottom - 1, e.CellBounds.Right - 1, e.CellBounds.Bottom - 1);
  109. }
  110. if (EraseCellValue.ToString().ToLower() == EraseCellDrawLineVEnd.ToLower() || EraseCellValue.ToString().ToLower() == EraseCellDrawLineVHEnd.ToLower())
  111. {
  112. // 画右边线
  113. e.Graphics.DrawLine(gridLinePen, e.CellBounds.Right - 1, e.CellBounds.Top, e.CellBounds.Right - 1, e.CellBounds.Bottom);
  114. }
  115. e.Handled = true;
  116. }
  117. }
  118. }
  119. /// <summary>
  120. /// 纵向合并,即合并数据项的值
  121. /// </summary>
  122. /// <param name="e"></param>
  123. private void DataGridViewEx_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
  124. {
  125. EraseCellPainting(e);
  126. }
  127. /// <summary>
  128. /// 绘制合并以后的值(纵向) 暂不使用
  129. /// </summary>
  130. /// <param name="e"></param>
  131. /// <param name="cellwidth"></param>
  132. /// <param name="UpRows"></param>
  133. /// <param name="DownRows"></param>
  134. /// <param name="count"></param>
  135. private void PaintingFont(System.Windows.Forms.DataGridViewCellPaintingEventArgs e, int cellwidth, int UpRows, int DownRows, int count)
  136. {
  137. string stValue = "";
  138. if (e.Value != DBNull.Value)
  139. {
  140. stValue = e.Value.ToString();
  141. }
  142. int fontheight = 0;
  143. int fontwidth = 0;
  144. using (SolidBrush fontBrush = new SolidBrush(e.CellStyle.ForeColor))
  145. {
  146. fontheight = (int)e.Graphics.MeasureString(e.Value.ToString(), e.CellStyle.Font).Height;
  147. fontwidth = (int)e.Graphics.MeasureString(e.Value.ToString(), e.CellStyle.Font).Width;
  148. int cellheight = e.CellBounds.Height;
  149. if (e.CellStyle.Alignment == DataGridViewContentAlignment.BottomCenter)
  150. {
  151. e.Graphics.DrawString(stValue, e.CellStyle.Font, fontBrush, e.CellBounds.X + (cellwidth - fontwidth) / 2, e.CellBounds.Y + cellheight * DownRows - fontheight);
  152. }
  153. else if (e.CellStyle.Alignment == DataGridViewContentAlignment.BottomLeft)
  154. {
  155. e.Graphics.DrawString(stValue, e.CellStyle.Font, fontBrush, e.CellBounds.X, e.CellBounds.Y + cellheight * DownRows - fontheight);
  156. }
  157. else if (e.CellStyle.Alignment == DataGridViewContentAlignment.BottomRight)
  158. {
  159. e.Graphics.DrawString(stValue, e.CellStyle.Font, fontBrush, e.CellBounds.X + cellwidth - fontwidth, e.CellBounds.Y + cellheight * DownRows - fontheight);
  160. }
  161. else if (e.CellStyle.Alignment == DataGridViewContentAlignment.MiddleCenter)
  162. {
  163. e.Graphics.DrawString(stValue, e.CellStyle.Font, fontBrush, e.CellBounds.X + (cellwidth - fontwidth) / 2, e.CellBounds.Y - cellheight * (UpRows - 1) + (cellheight * count - fontheight) / 2);
  164. }
  165. else if (e.CellStyle.Alignment == DataGridViewContentAlignment.MiddleLeft)
  166. {
  167. e.Graphics.DrawString(stValue, e.CellStyle.Font, fontBrush, e.CellBounds.X, e.CellBounds.Y - cellheight * (UpRows - 1) + (cellheight * count - fontheight) / 2);
  168. }
  169. else if (e.CellStyle.Alignment == DataGridViewContentAlignment.MiddleRight)
  170. {
  171. e.Graphics.DrawString(stValue, e.CellStyle.Font, fontBrush, e.CellBounds.X + cellwidth - fontwidth, e.CellBounds.Y - cellheight * (UpRows - 1) + (cellheight * count - fontheight) / 2);
  172. }
  173. else if (e.CellStyle.Alignment == DataGridViewContentAlignment.TopCenter)
  174. {
  175. e.Graphics.DrawString(stValue, e.CellStyle.Font, fontBrush, e.CellBounds.X + (cellwidth - fontwidth) / 2, e.CellBounds.Y - cellheight * (UpRows - 1));
  176. }
  177. else if (e.CellStyle.Alignment == DataGridViewContentAlignment.TopLeft)
  178. {
  179. e.Graphics.DrawString(stValue, e.CellStyle.Font, fontBrush, e.CellBounds.X, e.CellBounds.Y - cellheight * (UpRows - 1));
  180. }
  181. else if (e.CellStyle.Alignment == DataGridViewContentAlignment.TopRight)
  182. {
  183. e.Graphics.DrawString(stValue, e.CellStyle.Font, fontBrush, e.CellBounds.X + cellwidth - fontwidth, e.CellBounds.Y - cellheight * (UpRows - 1));
  184. }
  185. else
  186. {
  187. e.Graphics.DrawString(stValue, e.CellStyle.Font, fontBrush, e.CellBounds.X + (cellwidth - fontwidth) / 2, e.CellBounds.Y - cellheight * (UpRows - 1) + (cellheight * count - fontheight) / 2);
  188. }
  189. }
  190. }
  191. bool _isCopyCellValue = true;
  192. /// <summary>
  193. /// 是否能复制单元格的Value值
  194. /// </summary>
  195. [
  196. Category("CollapseDataGridViewProperties"),
  197. Description("是否能复制单元格的Value值"),
  198. Bindable(true)
  199. ]
  200. public bool IsCopyCellValue
  201. {
  202. get { return _isCopyCellValue; }
  203. set { _isCopyCellValue = value; }
  204. }
  205. public ContextMenuStrip conMenu = new ContextMenuStrip();
  206. void DataGridViewEx_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
  207. {
  208. if (this.Rows.Count > 0)
  209. {
  210. if (this.CurrentRow != null)
  211. {
  212. if (e.ColumnIndex >= 0 && e.RowIndex >= 0)
  213. {
  214. if (e.Button == System.Windows.Forms.MouseButtons.Right)
  215. {
  216. if (IsCopyCellValue)
  217. {
  218. this.conMenu.Items.Clear();
  219. conMenu.Show(MousePosition.X, MousePosition.Y);//弹出操作菜单
  220. conMenu.ItemClicked -= conMenu_ItemClicked;
  221. conMenu.ItemClicked += conMenu_ItemClicked;
  222. ToolStripMenuItem item = new ToolStripMenuItem();
  223. item.Text = "复制" + this.Columns[e.ColumnIndex].HeaderText;
  224. item.Tag = this.CurrentRow.Index + "|" + e.ColumnIndex;
  225. item.Name = "复制列";
  226. conMenu.Items.Add(item);
  227. conMenu.Show();
  228. }
  229. }
  230. }
  231. else if (e.RowIndex == -1)
  232. {
  233. if (this.SelectedRows.Count > 3)
  234. {
  235. if (e.Button == System.Windows.Forms.MouseButtons.Right)
  236. {
  237. try
  238. {
  239. decimal decAoumnt = 0;
  240. for (int i = 0; i < this.Rows.Count; i++)
  241. {
  242. decAoumnt += Convert.ToDecimal(this.Rows[i].Cells[e.ColumnIndex].Value);
  243. }
  244. MessageBoxCustom.Show(decAoumnt.ToString().Trim());
  245. }
  246. catch { }
  247. }
  248. }
  249. }
  250. }
  251. }
  252. }
  253. public delegate void DataGridView_ConMenu_ItemClicked(object sender, ToolStripItemClickedEventArgs e);
  254. /// <summary>
  255. /// 用event 关键字声明事件对象
  256. /// </summary>
  257. [Category("控件扩展事件"), Description("列表右击显示菜单事件")]
  258. public event DataGridView_ConMenu_ItemClicked DataGridViewConMenu_ItemClicked;
  259. void conMenu_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
  260. {
  261. ToolStripItem item = e.ClickedItem;
  262. if (!string.IsNullOrEmpty(item.Name) && item.Name.Trim() == "复制列")
  263. {
  264. if (!string.IsNullOrEmpty(item.Text.Trim()) && item.Tag != null)
  265. {
  266. string[] StrTag = item.Tag.ToString().Trim().Split('|');
  267. Clipboard.SetDataObject(this.Rows[Convert.ToInt32(StrTag[0])].Cells[Convert.ToInt32(StrTag[1])].Value.ToString().Trim());
  268. }
  269. }
  270. else
  271. {
  272. if (this.DataGridViewConMenu_ItemClicked != null)
  273. { this.DataGridViewConMenu_ItemClicked(sender, e); }
  274. }
  275. }
  276. /// <summary>
  277. /// 刷新主题
  278. /// </summary>
  279. public void RefreshTheme()
  280. {
  281. try
  282. {
  283. // BackgroundColor = Color.White; //背景颜色
  284. // BorderStyle = BorderStyle.Fixed3D; //边框样式
  285. // ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.None; //列标题边框样式
  286. // GridColor = Color.Silver; //单元格网状颜色
  287. // AllowUserToAddRows = false; //是否显示增加列
  288. // AllowUserToDeleteRows = false; //是否允许删除
  289. // AllowUserToOrderColumns = true; //是否手动放置
  290. SelectionMode = DataGridViewSelectionMode.FullRowSelect;
  291. AllowUserToResizeRows = false;//不可设置行高
  292. // RowsDefaultCellStyle.SelectionBackColor = Color.SkyBlue;
  293. // //改变标题的高度;
  294. // ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.EnableResizing;
  295. // ColumnHeadersHeight = 50;
  296. // //设置标题内容居中显示;
  297. // ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
  298. //// RowHeadersDefaultCellStyle.Alignment =DataGridViewCellStyle;
  299. System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle();
  300. System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle2 = new System.Windows.Forms.DataGridViewCellStyle();
  301. AllowUserToAddRows = false;
  302. AllowUserToDeleteRows = false;
  303. dataGridViewCellStyle1.BackColor = System.Drawing.Color.LightCyan;
  304. AlternatingRowsDefaultCellStyle = dataGridViewCellStyle1;
  305. BackgroundColor = System.Drawing.Color.White;
  306. BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
  307. ColumnHeadersBorderStyle = System.Windows.Forms.DataGridViewHeaderBorderStyle.Single;
  308. dataGridViewCellStyle2.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter;//211, 223, 240
  309. dataGridViewCellStyle2.BackColor = System.Drawing.Color.FromArgb(43, 108, 150);//标题背景色
  310. dataGridViewCellStyle2.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
  311. dataGridViewCellStyle2.ForeColor = System.Drawing.Color.White; //标题文字色
  312. dataGridViewCellStyle2.SelectionBackColor = System.Drawing.SystemColors.Highlight;
  313. dataGridViewCellStyle2.SelectionForeColor = System.Drawing.SystemColors.HighlightText;
  314. ColumnHeadersDefaultCellStyle = dataGridViewCellStyle2;
  315. ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
  316. this.ColumnHeadersHeight = 24;
  317. EnableHeadersVisualStyles = false;
  318. GridColor = System.Drawing.SystemColors.GradientInactiveCaption;
  319. //ReadOnly = true;
  320. RowHeadersVisible = false;
  321. RowTemplate.Height = 23;
  322. RowTemplate.ReadOnly = true;
  323. }
  324. catch { }
  325. }
  326. /// <summary>
  327. ///
  328. /// </summary>
  329. protected override void CreateHandle()
  330. {
  331. if (!IsHandleCreated)
  332. {
  333. try
  334. { base.CreateHandle(); }
  335. catch { }
  336. finally
  337. {
  338. if (!IsHandleCreated)
  339. { base.RecreateHandle(); }
  340. }
  341. }
  342. }
  343. /// <summary>
  344. ///
  345. /// </summary>
  346. /// <param name="sender"></param>
  347. /// <param name="e"></param>
  348. void DataGridViewEx_Paint(object sender, PaintEventArgs e)
  349. {
  350. try
  351. {
  352. Pen p = new Pen(LYFZ.ComponentLibrary.GetUIResources.DataGridViewExBorderColor);
  353. // p.Color = LYFZ.ComponentLibrary.GetUIResources.DataGridViewExBorderColor;
  354. e.Graphics.DrawRectangle(p, new Rectangle(0, 0, this.Width - 1, this.Height - 1));
  355. }
  356. catch
  357. { }
  358. }
  359. /// <summary>
  360. /// 数据是否完成邦定
  361. /// </summary>
  362. bool isCompleteBonding = false;
  363. /// <summary>
  364. /// 数据是否完成邦定
  365. /// </summary>
  366. public bool IsCompleteBonding
  367. {
  368. get { return isCompleteBonding; }
  369. set { isCompleteBonding = value; }
  370. }
  371. //创建一个委托,是为访问DataGridVie控件服务的。
  372. public delegate void UpdateDataGridView();
  373. /// <summary>
  374. /// 清空所有行
  375. /// </summary>
  376. public void ClearAllRows()
  377. {
  378. System.Data.DataTable dtble = (System.Data.DataTable)this.DataSource;
  379. if (dtble != null)
  380. { dtble.Rows.Clear(); }
  381. }
  382. /// <summary>
  383. /// 显示标题菜单
  384. /// </summary>
  385. System.Windows.Forms.ContextMenuStrip displayTitleMenu = null;
  386. /// <summary>
  387. /// 设置排序
  388. /// </summary>
  389. /// <param name="columnName"></param>
  390. /// <param name="direction"></param>
  391. public void SetSort(string columnName, ListSortDirection direction)
  392. { this.Sort(this.Columns[columnName], direction); }
  393. string _DisplayIndexValue = "";
  394. string gridViewUniquelyIdentify = "";
  395. /// <summary>
  396. /// GridViewUniquelyIdentify唯一标识不能为空
  397. /// </summary>
  398. public string GridViewUniquelyIdentify
  399. {
  400. get { return gridViewUniquelyIdentify; }
  401. set
  402. {
  403. try
  404. {
  405. try
  406. { gridViewUniquelyIdentify = value + "_" + this.Parent.Name + "_" + this.Name; }
  407. catch
  408. { gridViewUniquelyIdentify = value + "_" + this.Name; }
  409. }
  410. catch
  411. { gridViewUniquelyIdentify = value; }
  412. }
  413. }
  414. /// <summary>
  415. /// 获取排序对象 请在邦定数据前获取
  416. /// </summary>
  417. /// <param name="defaultSortField"></param>
  418. /// <param name="defaultSortDirection"></param>
  419. /// <returns></returns>
  420. public SortedColumnModel GetSortedColumnModel(string defaultSortField = "id", ListSortDirection defaultSortDirection = ListSortDirection.Descending)
  421. {
  422. SortedColumnModel model = new SortedColumnModel();
  423. try
  424. {
  425. DataGridViewColumn sortColumn = this.SortedColumn;
  426. string orderStr = " " + defaultSortField + " desc ";
  427. string columnName = defaultSortField;
  428. if (defaultSortDirection == ListSortDirection.Descending)
  429. { orderStr = " " + defaultSortField + " desc "; }
  430. else
  431. { orderStr = " " + defaultSortField + " asc "; }
  432. ListSortDirection Direction = defaultSortDirection;
  433. if (sortColumn != null)
  434. {
  435. columnName = sortColumn.Name;
  436. switch (this.SortOrder)
  437. {
  438. case SortOrder.Ascending:
  439. orderStr = "[" + sortColumn.Name + "] asc ";
  440. Direction = ListSortDirection.Ascending;
  441. break;
  442. case SortOrder.Descending:
  443. orderStr = "[" + sortColumn.Name + "] desc ";
  444. Direction = ListSortDirection.Descending;
  445. break;
  446. default: break;
  447. }
  448. }
  449. model.Direction = Direction;
  450. model.OrderStr = orderStr.Trim();
  451. model.SortColumn = sortColumn;
  452. model.ColumnName = columnName;
  453. }
  454. catch { }
  455. return model;
  456. }
  457. /// <summary>
  458. /// 导出数据
  459. /// </summary>
  460. public void ExportDataTable()
  461. {
  462. DataGridViewExport.DataToExcel(this);
  463. }
  464. /// <summary>
  465. /// 导出数据
  466. /// </summary>
  467. public void DataToExcelPayroll(string StrExeclName = "")
  468. {
  469. DataGridViewExport.DataToExcelPayroll(this, StrExeclName);
  470. }
  471. /// <summary>
  472. /// 排序对象
  473. /// </summary>
  474. public class SortedColumnModel
  475. {
  476. public SortedColumnModel()
  477. { }
  478. DataGridViewColumn sortColumn = new DataGridViewColumn();
  479. /// <summary>
  480. /// 当前的排序字段,请在邦定数据前获取
  481. /// </summary>
  482. public DataGridViewColumn SortColumn
  483. {
  484. get { return sortColumn; }
  485. set { sortColumn = value; }
  486. }
  487. string orderStr = " id desc ";
  488. /// <summary>
  489. /// 获取排序字符串
  490. /// </summary>
  491. public string OrderStr
  492. {
  493. get { return orderStr; }
  494. set { orderStr = value; }
  495. }
  496. string columnName = "id";
  497. /// <summary>
  498. /// 排序字段名
  499. /// </summary>
  500. public string ColumnName
  501. {
  502. get { return columnName; }
  503. set { columnName = value; }
  504. }
  505. ListSortDirection direction = ListSortDirection.Descending;
  506. /// <summary>
  507. /// 排序方式
  508. /// </summary>
  509. public ListSortDirection Direction
  510. {
  511. get { return direction; }
  512. set { direction = value; }
  513. }
  514. }
  515. }
  516. #region
  517. public class DataGridViewExport
  518. {
  519. /// <summary>
  520. /// 导出DataGridView数据 以文本形式导出
  521. /// </summary>
  522. /// <param name="m_DataView"></param>
  523. public static void DataTableToExcel(DataTable m_DataView, bool IsShowSave = true, string StrFileName = "", string ExportOKPrompt="")
  524. {
  525. string FileName = "";
  526. if (IsShowSave)
  527. {
  528. SaveFileDialog saveFile = new SaveFileDialog();
  529. saveFile.Title = "导出数据报表文件";
  530. saveFile.Filter = "EXECL文件(*.xls) |*.xls |文本文件(*.txt) |*.txt |所有文件(*.*) |*.*";
  531. saveFile.FilterIndex = 1;
  532. DialogResult drst = saveFile.ShowDialog();
  533. if (drst == DialogResult.No || drst == DialogResult.Cancel || drst == DialogResult.No || drst == DialogResult.Abort)
  534. { return; }
  535. FileName = saveFile.FileName;
  536. }
  537. else
  538. { FileName = StrFileName; }
  539. //定义表格内数据的行数和列数
  540. int rowscount = m_DataView.Rows.Count;
  541. int colscount = m_DataView.Columns.Count;
  542. //行数必须大于0 列数必须大于0
  543. if (rowscount <= 0 || colscount <= 0)
  544. {
  545. MessageBoxCustom.Show("没有数据可供保存 ");
  546. return;
  547. }
  548. //行数不可以大于65536
  549. if (rowscount > 65536)
  550. {
  551. MessageBoxCustom.Show("数据记录数太多(最多不能超过65536条),不能保存 ");
  552. return;
  553. }
  554. //列数不可以大于255
  555. if (colscount > 255)
  556. {
  557. MessageBoxCustom.Show("数据记录列数太多,不能保存 ");
  558. return;
  559. }
  560. if (File.Exists(FileName))
  561. File.Delete(FileName);
  562. FileStream objFileStream;
  563. StreamWriter objStreamWriter;
  564. string strLine = "";
  565. objFileStream = new FileStream(FileName, FileMode.OpenOrCreate, FileAccess.Write);
  566. objStreamWriter = new StreamWriter(objFileStream, System.Text.Encoding.Unicode);
  567. for (int i = 0; i < m_DataView.Columns.Count; i++)
  568. {
  569. strLine = strLine + m_DataView.Columns[i].ColumnName.Trim() + Convert.ToChar(9);
  570. }
  571. objStreamWriter.WriteLine(strLine);
  572. strLine = "";
  573. for (int i = 0; i < m_DataView.Rows.Count; i++)
  574. {
  575. for (int j = 0; j < m_DataView.Columns.Count; j++)
  576. {
  577. if (m_DataView.Rows[i][j].ToString().Trim() == null)
  578. strLine = strLine + " " + Convert.ToChar(9);
  579. else
  580. {
  581. string rowstr = "";
  582. rowstr = m_DataView.Rows[i][j].ToString().Trim();
  583. rowstr = rowstr.Replace("\r\n", " ");
  584. rowstr = rowstr.Replace("\t", " ");
  585. rowstr = rowstr.Replace("\r", " ");
  586. rowstr = rowstr.Replace("\n", " ");
  587. rowstr = rowstr.Trim();
  588. try
  589. {
  590. string tempValue = rowstr.Split(',')[0].Trim();
  591. if (tempValue.Length == 11)
  592. {
  593. long tempI = 0;
  594. if (long.TryParse(tempValue, out tempI))
  595. { rowstr = "'" + rowstr; }
  596. }
  597. }
  598. catch
  599. { }
  600. strLine = strLine + rowstr + Convert.ToChar(9);
  601. }
  602. }
  603. objStreamWriter.WriteLine(strLine);
  604. strLine = "";
  605. }
  606. objStreamWriter.Close();
  607. objFileStream.Close();
  608. if (string.IsNullOrEmpty(ExportOKPrompt))
  609. { MessageBoxCustom.Show("导出成功"); }
  610. else
  611. { MessageBoxCustom.Show(ExportOKPrompt); }
  612. }
  613. /// <summary>
  614. /// 导出DataGridView数据 以文本形式导出
  615. /// </summary>
  616. /// <param name="m_DataView"></param>
  617. public static void DataToExcel(DataGridView m_DataView)
  618. {
  619. SaveFileDialog saveFile = new SaveFileDialog();
  620. saveFile.Title = "导出数据报表文件";
  621. saveFile.Filter = "EXECL文件(*.xls) |*.xls |文本文件(*.txt) |*.txt |所有文件(*.*) |*.*";
  622. saveFile.FilterIndex = 1;
  623. if (saveFile.ShowDialog() == DialogResult.OK)
  624. {
  625. //定义表格内数据的行数和列数
  626. int rowscount = m_DataView.Rows.GetRowCount(DataGridViewElementStates.Visible);
  627. int colscount = m_DataView.Columns.GetColumnCount(DataGridViewElementStates.Visible);
  628. //行数必须大于0 列数必须大于0
  629. if (rowscount <= 0 || colscount <= 0)
  630. {
  631. MessageBoxCustom.Show("没有数据可供保存 ");
  632. return;
  633. }
  634. //行数不可以大于65536
  635. if (rowscount > 65536)
  636. {
  637. MessageBoxCustom.Show("数据记录数太多(最多不能超过65536条),不能保存 ");
  638. return;
  639. }
  640. //列数不可以大于255
  641. if (colscount > 255)
  642. {
  643. MessageBoxCustom.Show("数据记录列数太多,不能保存 ");
  644. return;
  645. }
  646. string FileName = saveFile.FileName;
  647. try
  648. {
  649. if (LYFZ.WinAPI.CustomPublicMethod.DataGridViewToExcel(FileName,m_DataView))
  650. {
  651. MessageBoxCustom.Show("导出成功");
  652. }
  653. else
  654. {
  655. MessageBoxCustom.Show("导出失败,请重试!");
  656. }
  657. }
  658. catch (Exception ex){
  659. MessageBoxCustom.Show("导出失败,原因:" + ex.Message);
  660. }
  661. }
  662. }
  663. /// <summary>
  664. /// 导出DataGridView数据 以文本形式导出(只用于工资管理)
  665. /// </summary>
  666. /// <param name="m_DataView"></param>
  667. public static void DataToExcelPayroll(DataGridView m_DataView, string StrExeclName)
  668. {
  669. SaveFileDialog saveFileDialog = new SaveFileDialog();
  670. saveFileDialog.Filter = "Execl files (*.xls)|*.xls";
  671. saveFileDialog.FilterIndex = 0;
  672. saveFileDialog.RestoreDirectory = true;
  673. saveFileDialog.CreatePrompt = true;
  674. saveFileDialog.FileName = StrExeclName;
  675. saveFileDialog.Title = "保存为Excel文件";
  676. saveFileDialog.CreatePrompt = false;
  677. saveFileDialog.OverwritePrompt = true;
  678. saveFileDialog.ShowDialog();
  679. Stream myStream;
  680. if (saveFileDialog.FileName.IndexOf(":") < 0) return; //被点了"取消"
  681. myStream = saveFileDialog.OpenFile();
  682. StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));
  683. string str = "";
  684. Cursor.Current = Cursors.WaitCursor;
  685. try
  686. {
  687. //写标题
  688. for (int i = 0; i < m_DataView.ColumnCount; i++)
  689. {
  690. if (m_DataView.Columns[i].Visible)
  691. {
  692. if (i > 0)
  693. { str += "\t"; }
  694. str += m_DataView.Columns[i].HeaderText;
  695. }
  696. }
  697. sw.WriteLine(str);
  698. //写所有内容
  699. decimal decAllAmount = 0;
  700. for (int j = 0; j < m_DataView.Rows.Count; j++)
  701. {
  702. decAllAmount += Convert.ToDecimal(m_DataView.Rows[j].Cells["Column3"].Value);
  703. PaintedColumn(m_DataView, j, sw);
  704. }
  705. sw.WriteLine("总计:" + decAllAmount.ToString("n2"));
  706. sw.WriteLine("\r\n");
  707. sw.WriteLine("******以下为分类统计******");
  708. sw.WriteLine("\r\n");
  709. string StrSortColumnName = "Column8";// "Column17";
  710. m_DataView.Sort(m_DataView.Columns[StrSortColumnName], ListSortDirection.Ascending);
  711. decAllAmount = 0;
  712. string StrSortName = "";
  713. DataTable dt_tbl = new DataTable();
  714. for (int i = 0; i < m_DataView.Columns.Count; i++)
  715. {
  716. if (m_DataView.Columns[i].Visible)
  717. { dt_tbl.Columns.Add(m_DataView.Columns[i].Name.Trim(), typeof(string)); }
  718. }
  719. for (int j = 0; j < m_DataView.Rows.Count; j++)
  720. {
  721. switch (m_DataView.Rows[j].Cells[StrSortColumnName].Value.ToString().Trim())
  722. {
  723. case "全款":
  724. case "预约收款":
  725. case "预约补款":
  726. DataRow newRow = dt_tbl.NewRow();
  727. for (int i = 0; i < m_DataView.Columns.Count; i++)
  728. {
  729. try
  730. {
  731. if (m_DataView.Columns[i].Visible)
  732. {
  733. if (m_DataView.Rows[j].Cells[i].Value != null)
  734. { newRow[m_DataView.Columns[i].Name] = m_DataView.Rows[j].Cells[i].Value.ToString().Trim(); }
  735. else
  736. { newRow[m_DataView.Columns[i].Name] = ""; }
  737. }
  738. }
  739. catch
  740. { }
  741. }
  742. dt_tbl.Rows.Add(newRow);
  743. break;
  744. default:
  745. if (j == 0)
  746. {
  747. StrSortName = m_DataView.Rows[j].Cells[StrSortColumnName].Value.ToString().Trim();
  748. decAllAmount += Convert.ToDecimal(m_DataView.Rows[j].Cells["Column3"].Value);
  749. PaintedColumn(m_DataView, j, sw);
  750. }
  751. else
  752. {
  753. if (m_DataView.Rows[j].Cells[StrSortColumnName].Value.ToString().Trim() == m_DataView.Rows[j - 1].Cells[StrSortColumnName].Value.ToString().Trim())
  754. {
  755. PaintedColumn(m_DataView, j, sw);
  756. }
  757. else
  758. {
  759. sw.WriteLine(StrSortName + "收款统计:" + decAllAmount.ToString("n2"));
  760. StrSortName = "";
  761. decAllAmount = 0;
  762. sw.WriteLine("\r\n");
  763. PaintedColumn(m_DataView, j, sw);
  764. }
  765. StrSortName = m_DataView.Rows[j].Cells[StrSortColumnName].Value.ToString().Trim();
  766. decAllAmount += Convert.ToDecimal(m_DataView.Rows[j].Cells["Column3"].Value);
  767. }
  768. break;
  769. }
  770. }
  771. sw.WriteLine(StrSortName + "收款统计:" + decAllAmount.ToString("n2"));
  772. sw.WriteLine("\r\n");
  773. decAllAmount = 0;
  774. dt_tbl.DefaultView.Sort = StrSortColumnName + " ASC";
  775. for (int j = 0; j < dt_tbl.Rows.Count; j++)
  776. {
  777. if (j == 0)
  778. {
  779. try
  780. { StrSortName = dt_tbl.Rows[j][StrSortColumnName].ToString().Trim(); }
  781. catch { }
  782. decAllAmount += Convert.ToDecimal(dt_tbl.Rows[j]["Column3"]);
  783. PaintedColumn(dt_tbl, j, sw);
  784. }
  785. else
  786. {
  787. if (dt_tbl.Rows[j][StrSortColumnName].ToString().Trim() == dt_tbl.Rows[j - 1][StrSortColumnName].ToString().Trim())
  788. {
  789. PaintedColumn(dt_tbl, j, sw);
  790. }
  791. else
  792. {
  793. sw.WriteLine(StrSortName + "收款统计:" + decAllAmount.ToString("n2"));
  794. StrSortName = "";
  795. decAllAmount = 0;
  796. sw.WriteLine("\r\n");
  797. PaintedColumn(dt_tbl, j, sw);
  798. }
  799. StrSortName = dt_tbl.Rows[j][StrSortColumnName].ToString().Trim();
  800. decAllAmount += Convert.ToDecimal(dt_tbl.Rows[j]["Column3"]);
  801. }
  802. }
  803. sw.WriteLine(StrSortName + "收款统计:" + decAllAmount.ToString("n2"));
  804. sw.Close();
  805. myStream.Close();
  806. MessageBoxCustom.Show("导出完毕!");
  807. }
  808. catch (Exception l)
  809. { MessageBox.Show(l.ToString()); }
  810. finally
  811. {
  812. sw.Close();
  813. myStream.Close();
  814. }
  815. }
  816. static void PaintedColumn(DataGridView m_DataView, int RowI, StreamWriter sw)
  817. {
  818. string tempStr = "";
  819. for (int k = 0; k < m_DataView.ColumnCount; k++)
  820. {
  821. if (m_DataView.Columns[k].Visible)
  822. {
  823. if (k > 0)
  824. { tempStr += "\t"; }
  825. if (m_DataView.Rows[RowI].Cells[k].Value != null)
  826. { tempStr += m_DataView.Rows[RowI].Cells[k].Value.ToString(); }
  827. else
  828. { tempStr += ""; }
  829. }
  830. }
  831. sw.WriteLine(tempStr);
  832. }
  833. static void PaintedColumn(DataTable dt_DataView, int RowI, StreamWriter sw)
  834. {
  835. string tempStr = "";
  836. for (int k = 0; k < dt_DataView.Columns.Count; k++)
  837. {
  838. if (k > 0)
  839. { tempStr += "\t"; }
  840. if (dt_DataView.Rows[RowI][k] != null && !string.IsNullOrEmpty(dt_DataView.Rows[RowI][k].ToString().Trim()))
  841. { tempStr += dt_DataView.Rows[RowI][k].ToString(); }
  842. else
  843. { tempStr += ""; }
  844. }
  845. sw.WriteLine(tempStr);
  846. }
  847. }
  848. #endregion
  849. }