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 { /// /// 实现分页后 /// public DataGridViewEx() : base() { try { RefreshTheme(); } catch { } this.Paint += DataGridViewEx_Paint; this.CellMouseDown += DataGridViewEx_CellMouseDown; this.CellPainting += DataGridViewEx_CellPainting; } /// /// 设置要隐藏的手机号字段名 /// 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 HidePhoneFindList = new List(); /// /// /// static List _HidePhoneCellsNameList = new List();//当前手机号字段列名 /// /// 要将字段值显示为“*”号的字段列名(当前手机号字段列名) /// public static List HidePhoneCellsNameList { get { return DataGridViewEx._HidePhoneCellsNameList; } } bool _EraseCell = false; /// /// 是否开启擦除单元格功能 /// 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"; } } /// /// 擦除单元格 /// /// 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; } } } /// /// 纵向合并,即合并数据项的值 /// /// private void DataGridViewEx_CellPainting(object sender, DataGridViewCellPaintingEventArgs e) { EraseCellPainting(e); } /// /// 绘制合并以后的值(纵向) 暂不使用 /// /// /// /// /// /// 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; /// /// 是否能复制单元格的Value值 /// [ 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); /// /// 用event 关键字声明事件对象 /// [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); } } } /// /// 刷新主题 /// 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 { } } /// /// /// protected override void CreateHandle() { if (!IsHandleCreated) { try { base.CreateHandle(); } catch { } finally { if (!IsHandleCreated) { base.RecreateHandle(); } } } } /// /// /// /// /// 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 { } } /// /// 数据是否完成邦定 /// bool isCompleteBonding = false; /// /// 数据是否完成邦定 /// public bool IsCompleteBonding { get { return isCompleteBonding; } set { isCompleteBonding = value; } } //创建一个委托,是为访问DataGridVie控件服务的。 public delegate void UpdateDataGridView(); /// /// 清空所有行 /// public void ClearAllRows() { System.Data.DataTable dtble = (System.Data.DataTable)this.DataSource; if (dtble != null) { dtble.Rows.Clear(); } } /// /// 显示标题菜单 /// System.Windows.Forms.ContextMenuStrip displayTitleMenu = null; /// /// 设置排序 /// /// /// public void SetSort(string columnName, ListSortDirection direction) { this.Sort(this.Columns[columnName], direction); } string _DisplayIndexValue = ""; string gridViewUniquelyIdentify = ""; /// /// GridViewUniquelyIdentify唯一标识不能为空 /// public string GridViewUniquelyIdentify { get { return gridViewUniquelyIdentify; } set { try { try { gridViewUniquelyIdentify = value + "_" + this.Parent.Name + "_" + this.Name; } catch { gridViewUniquelyIdentify = value + "_" + this.Name; } } catch { gridViewUniquelyIdentify = value; } } } /// /// 获取排序对象 请在邦定数据前获取 /// /// /// /// 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; } /// /// 导出数据 /// public void ExportDataTable() { DataGridViewExport.DataToExcel(this); } /// /// 导出数据 /// public void DataToExcelPayroll(string StrExeclName = "") { DataGridViewExport.DataToExcelPayroll(this, StrExeclName); } /// /// 排序对象 /// public class SortedColumnModel { public SortedColumnModel() { } DataGridViewColumn sortColumn = new DataGridViewColumn(); /// /// 当前的排序字段,请在邦定数据前获取 /// public DataGridViewColumn SortColumn { get { return sortColumn; } set { sortColumn = value; } } string orderStr = " id desc "; /// /// 获取排序字符串 /// public string OrderStr { get { return orderStr; } set { orderStr = value; } } string columnName = "id"; /// /// 排序字段名 /// public string ColumnName { get { return columnName; } set { columnName = value; } } ListSortDirection direction = ListSortDirection.Descending; /// /// 排序方式 /// public ListSortDirection Direction { get { return direction; } set { direction = value; } } } } #region public class DataGridViewExport { /// /// 导出DataGridView数据 以文本形式导出 /// /// 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); } } /// /// 导出DataGridView数据 以文本形式导出 /// /// 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); } } } /// /// 导出DataGridView数据 以文本形式导出(只用于工资管理) /// /// 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 }