123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882 |
- using System;
- using System.Collections.Generic;
- using System.Text;
- using System.Windows.Forms;
- using System.IO;
- using System.Drawing;
- using System.Drawing.Drawing2D;
- using System.ComponentModel;
- using System.Data;
- namespace LYFZ.ComponentLibrary
- {
- public class DataGridViewEx : System.Windows.Forms.DataGridView
- {
- /// <summary>
- /// 实现分页后
- /// </summary>
- public DataGridViewEx()
- : base()
- {
- try
- { RefreshTheme(); }
- catch { }
- this.Paint += DataGridViewEx_Paint;
- this.CellMouseDown += DataGridViewEx_CellMouseDown;
- this.CellPainting += DataGridViewEx_CellPainting;
- }
- /// <summary>
- /// 设置要隐藏的手机号字段名
- /// </summary>
- void SetHidePhoneCellsName()
- {
- if (this.Columns != null)
- {
- HidePhoneFindList.Clear();
- for (int i = 0; i < this.Columns.Count; i++)
- {
- DataGridViewColumn Column = this.Columns[i];
- if (_HidePhoneCellsNameList.Contains(Column.Name) || _HidePhoneCellsNameList.Contains(Column.HeaderText))
- {
- HidePhoneFindList.Add(Column.Name);
- }
- }
- }
- }
- // string[] HidePhoneFinds = "客户电话,电话,固定电话,介绍人电话,手机号码,本人手机,老公手机".Split(',');
- List<string> HidePhoneFindList = new List<string>();
- /// <summary>
- ///
- /// </summary>
- static List<string> _HidePhoneCellsNameList = new List<string>();//当前手机号字段列名
- /// <summary>
- /// 要将字段值显示为“*”号的字段列名(当前手机号字段列名)
- /// </summary>
- public static List<string> HidePhoneCellsNameList
- {
- get { return DataGridViewEx._HidePhoneCellsNameList; }
- }
- bool _EraseCell = false;
- /// <summary>
- /// 是否开启擦除单元格功能
- /// </summary>
- public bool EraseCell
- {
- get { return _EraseCell; }
- set { _EraseCell = value; }
- }
- public string EraseCellDrawLine
- {
- get { return "@EraseCellDrawLine@"; }
- }
- public string EraseCellDrawLineVEnd
- {
- get { return "@EraseCellDrawLine@VEnd"; }
- }
- public string EraseCellDrawLineHEnd
- {
- get { return "@EraseCellDrawLine@HEnd"; }
- }
- public string EraseCellDrawLineVHEnd
- {
- get { return "@EraseCellDrawLine@VHEnd"; }
- }
- /// <summary>
- /// 擦除单元格
- /// </summary>
- /// <param name="e"></param>
- void EraseCellPainting(DataGridViewCellPaintingEventArgs e)
- {
-
- if (EraseCell)
- {
- if (e.RowIndex < 0 || e.ColumnIndex < 0) { return; }
- Brush gridBrush = new SolidBrush(this.GridColor);
- SolidBrush backBrush = new SolidBrush(e.CellStyle.BackColor);
- object EraseCellValue = this.Rows[e.RowIndex].Cells[e.ColumnIndex].Tag;
- if (EraseCellValue != null && (EraseCellValue.ToString().ToLower().Contains(EraseCellDrawLine.ToLower())))
- {
- // cellwidth = e.CellBounds.Width;
- Pen gridLinePen = new Pen(gridBrush);
- if (this.Rows[e.RowIndex].Selected)
- {
- backBrush.Color = e.CellStyle.SelectionBackColor;
- }
- //以背景色填充
- e.Graphics.FillRectangle(backBrush, e.CellBounds);
- if (EraseCellValue.ToString().ToLower() == EraseCellDrawLineHEnd.ToLower() || EraseCellValue.ToString().ToLower() == EraseCellDrawLineVHEnd.ToLower())
- {
- //画下面的线
- e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left, e.CellBounds.Bottom - 1, e.CellBounds.Right - 1, e.CellBounds.Bottom - 1);
- }
- if (EraseCellValue.ToString().ToLower() == EraseCellDrawLineVEnd.ToLower() || EraseCellValue.ToString().ToLower() == EraseCellDrawLineVHEnd.ToLower())
- {
- // 画右边线
- e.Graphics.DrawLine(gridLinePen, e.CellBounds.Right - 1, e.CellBounds.Top, e.CellBounds.Right - 1, e.CellBounds.Bottom);
- }
- e.Handled = true;
- }
- }
-
- }
- /// <summary>
- /// 纵向合并,即合并数据项的值
- /// </summary>
- /// <param name="e"></param>
- private void DataGridViewEx_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
- {
- EraseCellPainting(e);
- }
- /// <summary>
- /// 绘制合并以后的值(纵向) 暂不使用
- /// </summary>
- /// <param name="e"></param>
- /// <param name="cellwidth"></param>
- /// <param name="UpRows"></param>
- /// <param name="DownRows"></param>
- /// <param name="count"></param>
- private void PaintingFont(System.Windows.Forms.DataGridViewCellPaintingEventArgs e, int cellwidth, int UpRows, int DownRows, int count)
- {
- string stValue = "";
- if (e.Value != DBNull.Value)
- {
- stValue = e.Value.ToString();
- }
- int fontheight = 0;
- int fontwidth = 0;
- using (SolidBrush fontBrush = new SolidBrush(e.CellStyle.ForeColor))
- {
- fontheight = (int)e.Graphics.MeasureString(e.Value.ToString(), e.CellStyle.Font).Height;
- fontwidth = (int)e.Graphics.MeasureString(e.Value.ToString(), e.CellStyle.Font).Width;
- int cellheight = e.CellBounds.Height;
- if (e.CellStyle.Alignment == DataGridViewContentAlignment.BottomCenter)
- {
- e.Graphics.DrawString(stValue, e.CellStyle.Font, fontBrush, e.CellBounds.X + (cellwidth - fontwidth) / 2, e.CellBounds.Y + cellheight * DownRows - fontheight);
- }
- else if (e.CellStyle.Alignment == DataGridViewContentAlignment.BottomLeft)
- {
- e.Graphics.DrawString(stValue, e.CellStyle.Font, fontBrush, e.CellBounds.X, e.CellBounds.Y + cellheight * DownRows - fontheight);
- }
- else if (e.CellStyle.Alignment == DataGridViewContentAlignment.BottomRight)
- {
- e.Graphics.DrawString(stValue, e.CellStyle.Font, fontBrush, e.CellBounds.X + cellwidth - fontwidth, e.CellBounds.Y + cellheight * DownRows - fontheight);
- }
- else if (e.CellStyle.Alignment == DataGridViewContentAlignment.MiddleCenter)
- {
- e.Graphics.DrawString(stValue, e.CellStyle.Font, fontBrush, e.CellBounds.X + (cellwidth - fontwidth) / 2, e.CellBounds.Y - cellheight * (UpRows - 1) + (cellheight * count - fontheight) / 2);
- }
- else if (e.CellStyle.Alignment == DataGridViewContentAlignment.MiddleLeft)
- {
- e.Graphics.DrawString(stValue, e.CellStyle.Font, fontBrush, e.CellBounds.X, e.CellBounds.Y - cellheight * (UpRows - 1) + (cellheight * count - fontheight) / 2);
- }
- else if (e.CellStyle.Alignment == DataGridViewContentAlignment.MiddleRight)
- {
- e.Graphics.DrawString(stValue, e.CellStyle.Font, fontBrush, e.CellBounds.X + cellwidth - fontwidth, e.CellBounds.Y - cellheight * (UpRows - 1) + (cellheight * count - fontheight) / 2);
- }
- else if (e.CellStyle.Alignment == DataGridViewContentAlignment.TopCenter)
- {
- e.Graphics.DrawString(stValue, e.CellStyle.Font, fontBrush, e.CellBounds.X + (cellwidth - fontwidth) / 2, e.CellBounds.Y - cellheight * (UpRows - 1));
- }
- else if (e.CellStyle.Alignment == DataGridViewContentAlignment.TopLeft)
- {
- e.Graphics.DrawString(stValue, e.CellStyle.Font, fontBrush, e.CellBounds.X, e.CellBounds.Y - cellheight * (UpRows - 1));
- }
- else if (e.CellStyle.Alignment == DataGridViewContentAlignment.TopRight)
- {
- e.Graphics.DrawString(stValue, e.CellStyle.Font, fontBrush, e.CellBounds.X + cellwidth - fontwidth, e.CellBounds.Y - cellheight * (UpRows - 1));
- }
- else
- {
- e.Graphics.DrawString(stValue, e.CellStyle.Font, fontBrush, e.CellBounds.X + (cellwidth - fontwidth) / 2, e.CellBounds.Y - cellheight * (UpRows - 1) + (cellheight * count - fontheight) / 2);
- }
- }
- }
- bool _isCopyCellValue = true;
- /// <summary>
- /// 是否能复制单元格的Value值
- /// </summary>
- [
- Category("CollapseDataGridViewProperties"),
- Description("是否能复制单元格的Value值"),
- Bindable(true)
- ]
- public bool IsCopyCellValue
- {
- get { return _isCopyCellValue; }
- set { _isCopyCellValue = value; }
- }
- public ContextMenuStrip conMenu = new ContextMenuStrip();
- void DataGridViewEx_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
- {
- if (this.Rows.Count > 0)
- {
- if (this.CurrentRow != null)
- {
- if (e.ColumnIndex >= 0 && e.RowIndex >= 0)
- {
- if (e.Button == System.Windows.Forms.MouseButtons.Right)
- {
- if (IsCopyCellValue)
- {
- this.conMenu.Items.Clear();
- conMenu.Show(MousePosition.X, MousePosition.Y);//弹出操作菜单
- conMenu.ItemClicked -= conMenu_ItemClicked;
- conMenu.ItemClicked += conMenu_ItemClicked;
- ToolStripMenuItem item = new ToolStripMenuItem();
- item.Text = "复制" + this.Columns[e.ColumnIndex].HeaderText;
- item.Tag = this.CurrentRow.Index + "|" + e.ColumnIndex;
- item.Name = "复制列";
- conMenu.Items.Add(item);
- conMenu.Show();
- }
- }
- }
- else if (e.RowIndex == -1)
- {
- if (this.SelectedRows.Count > 3)
- {
- if (e.Button == System.Windows.Forms.MouseButtons.Right)
- {
- try
- {
- decimal decAoumnt = 0;
- for (int i = 0; i < this.Rows.Count; i++)
- {
- decAoumnt += Convert.ToDecimal(this.Rows[i].Cells[e.ColumnIndex].Value);
- }
- MessageBoxCustom.Show(decAoumnt.ToString().Trim());
- }
- catch { }
- }
- }
- }
- }
- }
- }
- public delegate void DataGridView_ConMenu_ItemClicked(object sender, ToolStripItemClickedEventArgs e);
- /// <summary>
- /// 用event 关键字声明事件对象
- /// </summary>
- [Category("控件扩展事件"), Description("列表右击显示菜单事件")]
- public event DataGridView_ConMenu_ItemClicked DataGridViewConMenu_ItemClicked;
- void conMenu_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
- {
- ToolStripItem item = e.ClickedItem;
- if (!string.IsNullOrEmpty(item.Name) && item.Name.Trim() == "复制列")
- {
- if (!string.IsNullOrEmpty(item.Text.Trim()) && item.Tag != null)
- {
- string[] StrTag = item.Tag.ToString().Trim().Split('|');
- Clipboard.SetDataObject(this.Rows[Convert.ToInt32(StrTag[0])].Cells[Convert.ToInt32(StrTag[1])].Value.ToString().Trim());
- }
- }
- else
- {
- if (this.DataGridViewConMenu_ItemClicked != null)
- { this.DataGridViewConMenu_ItemClicked(sender, e); }
- }
- }
- /// <summary>
- /// 刷新主题
- /// </summary>
- public void RefreshTheme()
- {
- try
- {
- // BackgroundColor = Color.White; //背景颜色
- // BorderStyle = BorderStyle.Fixed3D; //边框样式
- // ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.None; //列标题边框样式
- // GridColor = Color.Silver; //单元格网状颜色
- // AllowUserToAddRows = false; //是否显示增加列
- // AllowUserToDeleteRows = false; //是否允许删除
- // AllowUserToOrderColumns = true; //是否手动放置
- SelectionMode = DataGridViewSelectionMode.FullRowSelect;
- AllowUserToResizeRows = false;//不可设置行高
- // RowsDefaultCellStyle.SelectionBackColor = Color.SkyBlue;
- // //改变标题的高度;
- // ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.EnableResizing;
- // ColumnHeadersHeight = 50;
- // //设置标题内容居中显示;
- // ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
- //// RowHeadersDefaultCellStyle.Alignment =DataGridViewCellStyle;
- System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle();
- System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle2 = new System.Windows.Forms.DataGridViewCellStyle();
- AllowUserToAddRows = false;
- AllowUserToDeleteRows = false;
- dataGridViewCellStyle1.BackColor = System.Drawing.Color.LightCyan;
- AlternatingRowsDefaultCellStyle = dataGridViewCellStyle1;
- BackgroundColor = System.Drawing.Color.White;
- BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
- ColumnHeadersBorderStyle = System.Windows.Forms.DataGridViewHeaderBorderStyle.Single;
- dataGridViewCellStyle2.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter;//211, 223, 240
- dataGridViewCellStyle2.BackColor = System.Drawing.Color.FromArgb(43, 108, 150);//标题背景色
- dataGridViewCellStyle2.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
- dataGridViewCellStyle2.ForeColor = System.Drawing.Color.White; //标题文字色
- dataGridViewCellStyle2.SelectionBackColor = System.Drawing.SystemColors.Highlight;
- dataGridViewCellStyle2.SelectionForeColor = System.Drawing.SystemColors.HighlightText;
- ColumnHeadersDefaultCellStyle = dataGridViewCellStyle2;
- ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
- this.ColumnHeadersHeight = 24;
- EnableHeadersVisualStyles = false;
- GridColor = System.Drawing.SystemColors.GradientInactiveCaption;
- //ReadOnly = true;
- RowHeadersVisible = false;
- RowTemplate.Height = 23;
- RowTemplate.ReadOnly = true;
- }
- catch { }
- }
- /// <summary>
- ///
- /// </summary>
- protected override void CreateHandle()
- {
- if (!IsHandleCreated)
- {
- try
- { base.CreateHandle(); }
- catch { }
- finally
- {
- if (!IsHandleCreated)
- { base.RecreateHandle(); }
- }
- }
- }
- /// <summary>
- ///
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- void DataGridViewEx_Paint(object sender, PaintEventArgs e)
- {
- try
- {
- Pen p = new Pen(LYFZ.ComponentLibrary.GetUIResources.DataGridViewExBorderColor);
- // p.Color = LYFZ.ComponentLibrary.GetUIResources.DataGridViewExBorderColor;
- e.Graphics.DrawRectangle(p, new Rectangle(0, 0, this.Width - 1, this.Height - 1));
- }
- catch
- { }
- }
- /// <summary>
- /// 数据是否完成邦定
- /// </summary>
- bool isCompleteBonding = false;
- /// <summary>
- /// 数据是否完成邦定
- /// </summary>
- public bool IsCompleteBonding
- {
- get { return isCompleteBonding; }
- set { isCompleteBonding = value; }
- }
- //创建一个委托,是为访问DataGridVie控件服务的。
- public delegate void UpdateDataGridView();
- /// <summary>
- /// 清空所有行
- /// </summary>
- public void ClearAllRows()
- {
- System.Data.DataTable dtble = (System.Data.DataTable)this.DataSource;
- if (dtble != null)
- { dtble.Rows.Clear(); }
- }
-
- /// <summary>
- /// 显示标题菜单
- /// </summary>
- System.Windows.Forms.ContextMenuStrip displayTitleMenu = null;
-
- /// <summary>
- /// 设置排序
- /// </summary>
- /// <param name="columnName"></param>
- /// <param name="direction"></param>
- public void SetSort(string columnName, ListSortDirection direction)
- { this.Sort(this.Columns[columnName], direction); }
- string _DisplayIndexValue = "";
-
- string gridViewUniquelyIdentify = "";
- /// <summary>
- /// GridViewUniquelyIdentify唯一标识不能为空
- /// </summary>
- public string GridViewUniquelyIdentify
- {
- get { return gridViewUniquelyIdentify; }
- set
- {
- try
- {
- try
- { gridViewUniquelyIdentify = value + "_" + this.Parent.Name + "_" + this.Name; }
- catch
- { gridViewUniquelyIdentify = value + "_" + this.Name; }
- }
- catch
- { gridViewUniquelyIdentify = value; }
- }
- }
- /// <summary>
- /// 获取排序对象 请在邦定数据前获取
- /// </summary>
- /// <param name="defaultSortField"></param>
- /// <param name="defaultSortDirection"></param>
- /// <returns></returns>
- public SortedColumnModel GetSortedColumnModel(string defaultSortField = "id", ListSortDirection defaultSortDirection = ListSortDirection.Descending)
- {
- SortedColumnModel model = new SortedColumnModel();
- try
- {
- DataGridViewColumn sortColumn = this.SortedColumn;
- string orderStr = " " + defaultSortField + " desc ";
- string columnName = defaultSortField;
- if (defaultSortDirection == ListSortDirection.Descending)
- { orderStr = " " + defaultSortField + " desc "; }
- else
- { orderStr = " " + defaultSortField + " asc "; }
- ListSortDirection Direction = defaultSortDirection;
- if (sortColumn != null)
- {
- columnName = sortColumn.Name;
- switch (this.SortOrder)
- {
- case SortOrder.Ascending:
- orderStr = "[" + sortColumn.Name + "] asc ";
- Direction = ListSortDirection.Ascending;
- break;
- case SortOrder.Descending:
- orderStr = "[" + sortColumn.Name + "] desc ";
- Direction = ListSortDirection.Descending;
- break;
- default: break;
- }
- }
- model.Direction = Direction;
- model.OrderStr = orderStr.Trim();
- model.SortColumn = sortColumn;
- model.ColumnName = columnName;
- }
- catch { }
- return model;
- }
- /// <summary>
- /// 导出数据
- /// </summary>
- public void ExportDataTable()
- {
- DataGridViewExport.DataToExcel(this);
- }
- /// <summary>
- /// 导出数据
- /// </summary>
- public void DataToExcelPayroll(string StrExeclName = "")
- {
- DataGridViewExport.DataToExcelPayroll(this, StrExeclName);
- }
- /// <summary>
- /// 排序对象
- /// </summary>
- public class SortedColumnModel
- {
- public SortedColumnModel()
- { }
- DataGridViewColumn sortColumn = new DataGridViewColumn();
- /// <summary>
- /// 当前的排序字段,请在邦定数据前获取
- /// </summary>
- public DataGridViewColumn SortColumn
- {
- get { return sortColumn; }
- set { sortColumn = value; }
- }
- string orderStr = " id desc ";
- /// <summary>
- /// 获取排序字符串
- /// </summary>
- public string OrderStr
- {
- get { return orderStr; }
- set { orderStr = value; }
- }
- string columnName = "id";
- /// <summary>
- /// 排序字段名
- /// </summary>
- public string ColumnName
- {
- get { return columnName; }
- set { columnName = value; }
- }
- ListSortDirection direction = ListSortDirection.Descending;
- /// <summary>
- /// 排序方式
- /// </summary>
- public ListSortDirection Direction
- {
- get { return direction; }
- set { direction = value; }
- }
- }
- }
- #region
- public class DataGridViewExport
- {
- /// <summary>
- /// 导出DataGridView数据 以文本形式导出
- /// </summary>
- /// <param name="m_DataView"></param>
- public static void DataTableToExcel(DataTable m_DataView, bool IsShowSave = true, string StrFileName = "", string ExportOKPrompt="")
- {
- string FileName = "";
- if (IsShowSave)
- {
- SaveFileDialog saveFile = new SaveFileDialog();
- saveFile.Title = "导出数据报表文件";
- saveFile.Filter = "EXECL文件(*.xls) |*.xls |文本文件(*.txt) |*.txt |所有文件(*.*) |*.*";
- saveFile.FilterIndex = 1;
- DialogResult drst = saveFile.ShowDialog();
- if (drst == DialogResult.No || drst == DialogResult.Cancel || drst == DialogResult.No || drst == DialogResult.Abort)
- { return; }
- FileName = saveFile.FileName;
- }
- else
- { FileName = StrFileName; }
- //定义表格内数据的行数和列数
- int rowscount = m_DataView.Rows.Count;
- int colscount = m_DataView.Columns.Count;
- //行数必须大于0 列数必须大于0
- if (rowscount <= 0 || colscount <= 0)
- {
- MessageBoxCustom.Show("没有数据可供保存 ");
- return;
- }
- //行数不可以大于65536
- if (rowscount > 65536)
- {
- MessageBoxCustom.Show("数据记录数太多(最多不能超过65536条),不能保存 ");
- return;
- }
- //列数不可以大于255
- if (colscount > 255)
- {
- MessageBoxCustom.Show("数据记录列数太多,不能保存 ");
- return;
- }
- if (File.Exists(FileName))
- File.Delete(FileName);
- FileStream objFileStream;
- StreamWriter objStreamWriter;
- string strLine = "";
- objFileStream = new FileStream(FileName, FileMode.OpenOrCreate, FileAccess.Write);
- objStreamWriter = new StreamWriter(objFileStream, System.Text.Encoding.Unicode);
- for (int i = 0; i < m_DataView.Columns.Count; i++)
- {
- strLine = strLine + m_DataView.Columns[i].ColumnName.Trim() + Convert.ToChar(9);
- }
- objStreamWriter.WriteLine(strLine);
- strLine = "";
- for (int i = 0; i < m_DataView.Rows.Count; i++)
- {
- for (int j = 0; j < m_DataView.Columns.Count; j++)
- {
- if (m_DataView.Rows[i][j].ToString().Trim() == null)
- strLine = strLine + " " + Convert.ToChar(9);
- else
- {
- string rowstr = "";
- rowstr = m_DataView.Rows[i][j].ToString().Trim();
- rowstr = rowstr.Replace("\r\n", " ");
- rowstr = rowstr.Replace("\t", " ");
- rowstr = rowstr.Replace("\r", " ");
- rowstr = rowstr.Replace("\n", " ");
- rowstr = rowstr.Trim();
- try
- {
- string tempValue = rowstr.Split(',')[0].Trim();
- if (tempValue.Length == 11)
- {
- long tempI = 0;
- if (long.TryParse(tempValue, out tempI))
- { rowstr = "'" + rowstr; }
- }
- }
- catch
- { }
- strLine = strLine + rowstr + Convert.ToChar(9);
- }
- }
- objStreamWriter.WriteLine(strLine);
- strLine = "";
- }
- objStreamWriter.Close();
- objFileStream.Close();
- if (string.IsNullOrEmpty(ExportOKPrompt))
- { MessageBoxCustom.Show("导出成功"); }
- else
- { MessageBoxCustom.Show(ExportOKPrompt); }
- }
- /// <summary>
- /// 导出DataGridView数据 以文本形式导出
- /// </summary>
- /// <param name="m_DataView"></param>
- public static void DataToExcel(DataGridView m_DataView)
- {
- SaveFileDialog saveFile = new SaveFileDialog();
- saveFile.Title = "导出数据报表文件";
- saveFile.Filter = "EXECL文件(*.xls) |*.xls |文本文件(*.txt) |*.txt |所有文件(*.*) |*.*";
- saveFile.FilterIndex = 1;
- if (saveFile.ShowDialog() == DialogResult.OK)
- {
- //定义表格内数据的行数和列数
- int rowscount = m_DataView.Rows.GetRowCount(DataGridViewElementStates.Visible);
- int colscount = m_DataView.Columns.GetColumnCount(DataGridViewElementStates.Visible);
- //行数必须大于0 列数必须大于0
- if (rowscount <= 0 || colscount <= 0)
- {
- MessageBoxCustom.Show("没有数据可供保存 ");
- return;
- }
- //行数不可以大于65536
- if (rowscount > 65536)
- {
- MessageBoxCustom.Show("数据记录数太多(最多不能超过65536条),不能保存 ");
- return;
- }
- //列数不可以大于255
- if (colscount > 255)
- {
- MessageBoxCustom.Show("数据记录列数太多,不能保存 ");
- return;
- }
- string FileName = saveFile.FileName;
- try
- {
- if (LYFZ.WinAPI.CustomPublicMethod.DataGridViewToExcel(FileName,m_DataView))
- {
- MessageBoxCustom.Show("导出成功");
- }
- else
- {
- MessageBoxCustom.Show("导出失败,请重试!");
- }
- }
- catch (Exception ex){
- MessageBoxCustom.Show("导出失败,原因:" + ex.Message);
- }
-
- }
- }
- /// <summary>
- /// 导出DataGridView数据 以文本形式导出(只用于工资管理)
- /// </summary>
- /// <param name="m_DataView"></param>
- public static void DataToExcelPayroll(DataGridView m_DataView, string StrExeclName)
- {
- SaveFileDialog saveFileDialog = new SaveFileDialog();
- saveFileDialog.Filter = "Execl files (*.xls)|*.xls";
- saveFileDialog.FilterIndex = 0;
- saveFileDialog.RestoreDirectory = true;
- saveFileDialog.CreatePrompt = true;
- saveFileDialog.FileName = StrExeclName;
- saveFileDialog.Title = "保存为Excel文件";
- saveFileDialog.CreatePrompt = false;
- saveFileDialog.OverwritePrompt = true;
- saveFileDialog.ShowDialog();
- Stream myStream;
- if (saveFileDialog.FileName.IndexOf(":") < 0) return; //被点了"取消"
- myStream = saveFileDialog.OpenFile();
- StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));
- string str = "";
- Cursor.Current = Cursors.WaitCursor;
- try
- {
- //写标题
- for (int i = 0; i < m_DataView.ColumnCount; i++)
- {
- if (m_DataView.Columns[i].Visible)
- {
- if (i > 0)
- { str += "\t"; }
- str += m_DataView.Columns[i].HeaderText;
- }
- }
- sw.WriteLine(str);
- //写所有内容
- decimal decAllAmount = 0;
- for (int j = 0; j < m_DataView.Rows.Count; j++)
- {
- decAllAmount += Convert.ToDecimal(m_DataView.Rows[j].Cells["Column3"].Value);
- PaintedColumn(m_DataView, j, sw);
- }
- sw.WriteLine("总计:" + decAllAmount.ToString("n2"));
- sw.WriteLine("\r\n");
- sw.WriteLine("******以下为分类统计******");
- sw.WriteLine("\r\n");
- string StrSortColumnName = "Column8";// "Column17";
- m_DataView.Sort(m_DataView.Columns[StrSortColumnName], ListSortDirection.Ascending);
- decAllAmount = 0;
- string StrSortName = "";
- DataTable dt_tbl = new DataTable();
- for (int i = 0; i < m_DataView.Columns.Count; i++)
- {
- if (m_DataView.Columns[i].Visible)
- { dt_tbl.Columns.Add(m_DataView.Columns[i].Name.Trim(), typeof(string)); }
- }
- for (int j = 0; j < m_DataView.Rows.Count; j++)
- {
- switch (m_DataView.Rows[j].Cells[StrSortColumnName].Value.ToString().Trim())
- {
- case "全款":
- case "预约收款":
- case "预约补款":
- DataRow newRow = dt_tbl.NewRow();
- for (int i = 0; i < m_DataView.Columns.Count; i++)
- {
- try
- {
- if (m_DataView.Columns[i].Visible)
- {
- if (m_DataView.Rows[j].Cells[i].Value != null)
- { newRow[m_DataView.Columns[i].Name] = m_DataView.Rows[j].Cells[i].Value.ToString().Trim(); }
- else
- { newRow[m_DataView.Columns[i].Name] = ""; }
- }
- }
- catch
- { }
- }
- dt_tbl.Rows.Add(newRow);
- break;
- default:
- if (j == 0)
- {
- StrSortName = m_DataView.Rows[j].Cells[StrSortColumnName].Value.ToString().Trim();
- decAllAmount += Convert.ToDecimal(m_DataView.Rows[j].Cells["Column3"].Value);
- PaintedColumn(m_DataView, j, sw);
- }
- else
- {
- if (m_DataView.Rows[j].Cells[StrSortColumnName].Value.ToString().Trim() == m_DataView.Rows[j - 1].Cells[StrSortColumnName].Value.ToString().Trim())
- {
- PaintedColumn(m_DataView, j, sw);
- }
- else
- {
- sw.WriteLine(StrSortName + "收款统计:" + decAllAmount.ToString("n2"));
- StrSortName = "";
- decAllAmount = 0;
- sw.WriteLine("\r\n");
- PaintedColumn(m_DataView, j, sw);
- }
- StrSortName = m_DataView.Rows[j].Cells[StrSortColumnName].Value.ToString().Trim();
- decAllAmount += Convert.ToDecimal(m_DataView.Rows[j].Cells["Column3"].Value);
- }
- break;
- }
- }
- sw.WriteLine(StrSortName + "收款统计:" + decAllAmount.ToString("n2"));
- sw.WriteLine("\r\n");
- decAllAmount = 0;
- dt_tbl.DefaultView.Sort = StrSortColumnName + " ASC";
- for (int j = 0; j < dt_tbl.Rows.Count; j++)
- {
- if (j == 0)
- {
- try
- { StrSortName = dt_tbl.Rows[j][StrSortColumnName].ToString().Trim(); }
- catch { }
- decAllAmount += Convert.ToDecimal(dt_tbl.Rows[j]["Column3"]);
- PaintedColumn(dt_tbl, j, sw);
- }
- else
- {
- if (dt_tbl.Rows[j][StrSortColumnName].ToString().Trim() == dt_tbl.Rows[j - 1][StrSortColumnName].ToString().Trim())
- {
- PaintedColumn(dt_tbl, j, sw);
- }
- else
- {
- sw.WriteLine(StrSortName + "收款统计:" + decAllAmount.ToString("n2"));
- StrSortName = "";
- decAllAmount = 0;
- sw.WriteLine("\r\n");
- PaintedColumn(dt_tbl, j, sw);
- }
- StrSortName = dt_tbl.Rows[j][StrSortColumnName].ToString().Trim();
- decAllAmount += Convert.ToDecimal(dt_tbl.Rows[j]["Column3"]);
- }
- }
- sw.WriteLine(StrSortName + "收款统计:" + decAllAmount.ToString("n2"));
- sw.Close();
- myStream.Close();
- MessageBoxCustom.Show("导出完毕!");
- }
- catch (Exception l)
- { MessageBox.Show(l.ToString()); }
- finally
- {
- sw.Close();
- myStream.Close();
- }
- }
- static void PaintedColumn(DataGridView m_DataView, int RowI, StreamWriter sw)
- {
- string tempStr = "";
- for (int k = 0; k < m_DataView.ColumnCount; k++)
- {
- if (m_DataView.Columns[k].Visible)
- {
- if (k > 0)
- { tempStr += "\t"; }
- if (m_DataView.Rows[RowI].Cells[k].Value != null)
- { tempStr += m_DataView.Rows[RowI].Cells[k].Value.ToString(); }
- else
- { tempStr += ""; }
- }
- }
- sw.WriteLine(tempStr);
- }
- static void PaintedColumn(DataTable dt_DataView, int RowI, StreamWriter sw)
- {
- string tempStr = "";
- for (int k = 0; k < dt_DataView.Columns.Count; k++)
- {
- if (k > 0)
- { tempStr += "\t"; }
- if (dt_DataView.Rows[RowI][k] != null && !string.IsNullOrEmpty(dt_DataView.Rows[RowI][k].ToString().Trim()))
- { tempStr += dt_DataView.Rows[RowI][k].ToString(); }
- else
- { tempStr += ""; }
- }
- sw.WriteLine(tempStr);
- }
- }
- #endregion
- }
|