首先在项目中引用
System.Drawing.Design;
System.Windows.Forms;
项目A:
说明:项目A要引用项目B
项目B
项目B在外面需要引用
Microsoft.Office.Interop.Excel
Microsoft.Office.Interop.Word
DataGridView导出Excel、Word、鼠标选定求和等扩展功能。
System.Drawing.Design;
System.Windows.Forms;
项目A:
说明:项目A要引用项目B
using System.Drawing; using System.Drawing.Design; using System.Windows.Forms; namespace HR.Control { public class DataGridViewC:DataGridView { /// <summary> /// 功能id /// </summary> public int formId; /// <summary> /// 列排序 /// </summary> public bool hRColumnSort = true; #region"定义右键菜单选项" internal System.Windows.Forms.ContextMenuStrip contextMenu = null; internal System.Windows.Forms.ToolStripMenuItem 输出到Excel文件ToolStripMenuItem; internal System.Windows.Forms.ToolStripSeparator ToolStripMenuItem1; internal System.Windows.Forms.ToolStripMenuItem 升序ToolStripMenuItem; internal System.Windows.Forms.ToolStripMenuItem 降序ToolStripMenuItem; internal System.Windows.Forms.ToolStripSeparator ToolStripMenuItem2; internal System.Windows.Forms.ToolStripMenuItem 复制ToolStripMenuItem; internal System.Windows.Forms.ToolStripMenuItem 复制到ToolStripMenuItem; internal System.Windows.Forms.ToolStripMenuItem MicrosoftWordToolStripMenuItem; internal System.Windows.Forms.ToolStripMenuItem MicrosoftExcelToolStripMenuItem; internal System.Windows.Forms.ToolStripMenuItem 另存为Excel文件; internal System.Windows.Forms.ToolStripSeparator ToolStripMenuItem3; internal System.Windows.Forms.ToolStripMenuItem 自动列宽ToolStripMenuItem; internal System.Windows.Forms.ToolStripSeparator ToolStripMenuItem4; internal System.Windows.Forms.ToolStripMenuItem 检索ToolStripMenuItem; internal System.Windows.Forms.ToolStripMenuItem 锁定到此行ToolStripMenuItem; internal System.Windows.Forms.ToolStripMenuItem 锁定到此列ToolStripMenuItem; #endregion /// <summary> /// 初始化DataGridViewC类的新实例。 /// </summary> /// <remarks></remarks> public DataGridViewC() { this.GridColor = Color.Green; this.BackgroundColor = Color.Linen; this.VirtualMode = true; this.AllowUserToAddRows = false; this.AllowUserToDeleteRows = false; this.AllowUserToOrderColumns = true; this.AllowUserToResizeColumns = true; this.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None; this.ReadOnly = true; this.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText; this.DataSource = null; this.DataSourceChanged+=new EventHandler(DataGridViewDataSourceChanged); AddContextMenu(); this.ContextMenuStrip = this.contextMenu; GC.Collect(); } /// <summary> /// 添加右键菜单项 /// </summary> private void AddContextMenu() { this.contextMenu = new ContextMenuStrip(); 输出到Excel文件ToolStripMenuItem=new ToolStripMenuItem(); ToolStripMenuItem1=new ToolStripSeparator(); 升序ToolStripMenuItem = new ToolStripMenuItem(); 降序ToolStripMenuItem=new ToolStripMenuItem(); ToolStripMenuItem2=new ToolStripSeparator(); 复制ToolStripMenuItem=new ToolStripMenuItem(); 复制到ToolStripMenuItem=new ToolStripMenuItem(); MicrosoftWordToolStripMenuItem=new ToolStripMenuItem(); MicrosoftExcelToolStripMenuItem=new ToolStripMenuItem(); 另存为Excel文件=new ToolStripMenuItem(); ToolStripMenuItem3=new ToolStripSeparator(); 自动列宽ToolStripMenuItem=new ToolStripMenuItem(); ToolStripMenuItem4=new ToolStripSeparator(); 检索ToolStripMenuItem=new ToolStripMenuItem(); 锁定到此行ToolStripMenuItem=new ToolStripMenuItem(); 锁定到此列ToolStripMenuItem = new ToolStripMenuItem(); 输出到Excel文件ToolStripMenuItem.Text = "输出到Excel文件"; 输出到Excel文件ToolStripMenuItem.Name = "输出到Excel文件ToolStripMenuItem"; ToolStripMenuItem1.Name = "ToolStripMenuItem1"; 升序ToolStripMenuItem.Text = "↑升序"; 升序ToolStripMenuItem.Name = "升序ToolStripMenuItem"; 降序ToolStripMenuItem.Text = "↓降序"; 降序ToolStripMenuItem.Name = "降序ToolStripMenuItem"; ToolStripMenuItem2.Name = "ToolStripMenuItem2"; 复制ToolStripMenuItem.Name = "复制ToolStripMenuItem"; 复制ToolStripMenuItem.Text = "复制(&C)"; 复制ToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.P; 复制到ToolStripMenuItem.Name = "复制到ToolStripMenuItem"; 复制到ToolStripMenuItem.Text = "复制到..."; 复制到ToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { this.MicrosoftWordToolStripMenuItem, this.MicrosoftExcelToolStripMenuItem }); MicrosoftExcelToolStripMenuItem.Name = "MicrosoftWordToolStripMenuItem"; MicrosoftExcelToolStripMenuItem.Text = "Microsoft.Excel"; MicrosoftWordToolStripMenuItem.Name = "MicrosoftWordToolStripMenuItem"; MicrosoftWordToolStripMenuItem.Text = "Microsoft.Word"; 另存为Excel文件.Name = "另存为Excel文件"; 另存为Excel文件.Text = "另存为Excel文件"; ToolStripMenuItem3.Name = "ToolStripMenuItem3"; 自动列宽ToolStripMenuItem.Name = "自动列宽ToolStripMenuItem"; 自动列宽ToolStripMenuItem.Text = "自动列宽"; ToolStripMenuItem4.Name = "ToolStripMenuItem4"; 检索ToolStripMenuItem.Name = "检索ToolStripMenuItem"; 检索ToolStripMenuItem.Text = "检索"; 锁定到此行ToolStripMenuItem.Name = "锁定到此行ToolStripMenuItem"; 锁定到此行ToolStripMenuItem.Text = "锁定到此行"; 锁定到此列ToolStripMenuItem.Name = "锁定到此列ToolStripMenuItem"; 锁定到此列ToolStripMenuItem.Text = "锁定到此列"; this.contextMenu.Items.AddRange(new ToolStripItem[]{ this.输出到Excel文件ToolStripMenuItem,this.另存为Excel文件,this.ToolStripMenuItem1,this.复制ToolStripMenuItem, this.复制到ToolStripMenuItem,this.ToolStripMenuItem2,this.检索ToolStripMenuItem,this.自动列宽ToolStripMenuItem,this.ToolStripMenuItem4, this.升序ToolStripMenuItem,this.降序ToolStripMenuItem,this.ToolStripMenuItem3,this.锁定到此行ToolStripMenuItem,this.锁定到此列ToolStripMenuItem}); this.contextMenu.Opening += new System.ComponentModel.CancelEventHandler(contextMenu_Opening); this.另存为Excel文件.Click += new EventHandler(另存为Excel文件_Click); this.输出到Excel文件ToolStripMenuItem.Click += new EventHandler(输出到Excel文件ToolStripMenuItem_Click); this.升序ToolStripMenuItem.Click += new EventHandler(AscendOrderSort); this.降序ToolStripMenuItem.Click += new EventHandler(DescOrderSort); this.复制ToolStripMenuItem.Click += new EventHandler(this.CopyData); this.MicrosoftExcelToolStripMenuItem.Click += new EventHandler(MicrosoftExcelToolStripMenuItem_Click); this.MicrosoftWordToolStripMenuItem.Click += new EventHandler(MicrosoftWordToolStripMenuItem_Click); this.自动列宽ToolStripMenuItem.Click += new EventHandler(AutoSizeColumn); this.锁定到此行ToolStripMenuItem.Click += new EventHandler(LockCurrR); this.锁定到此列ToolStripMenuItem.Click += new EventHandler(LockCurrC); this.检索ToolStripMenuItem.Click += new EventHandler(SearchGrid); } /// <summary> /// 检索操作 /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> /// <remarks></remarks> void SearchGrid(object sender, EventArgs e) { HR.Control.SearchSelect SS = new SearchSelect(); SS.FindAndSelect(this, SearchSelect.FindOption.FindText); } /// <summary> /// 锁定当前列 /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> /// <remarks></remarks> void LockCurrC(object sender, EventArgs e) { try { if (!this.锁定到此列ToolStripMenuItem.Checked) { this.锁定到此列ToolStripMenuItem.Checked = true; this.Columns[this.CurrentCell.ColumnIndex].Frozen = true; } else { this.锁定到此列ToolStripMenuItem.Checked = false; this.Columns[0].Frozen = false; } } catch { } } /// <summary> /// 锁定当前行 /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> /// <remarks></remarks> void LockCurrR(object sender, EventArgs e) { try { if (!this.锁定到此行ToolStripMenuItem.Checked) { this.Rows[CurrentCell.RowIndex].Frozen = true; this.锁定到此行ToolStripMenuItem.Checked = true; } else { this.Rows[0].Frozen = false; this.锁定到此行ToolStripMenuItem.Checked = false; } } catch { } } /// <summary> /// 自动列宽设置 /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> /// <remarks></remarks> void AutoSizeColumn(object sender, EventArgs e) { if (!this.自动列宽ToolStripMenuItem.Checked) { this.Cursor = Cursors.WaitCursor; this.自动列宽ToolStripMenuItem.Checked = true; this.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells; } else { this.自动列宽ToolStripMenuItem.Checked = false; this.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None; } this.Cursor = Cursors.Default; } /// <summary> /// 复制选中的数据到Word /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void MicrosoftWordToolStripMenuItem_Click(object sender, EventArgs e) { //引用项目B组件 HR.Control.DataGridViewOperation.Operate.OutputOperate OO = new HR.Control.DataGridViewOperation.Operate.OutputOperate(); OO.OutputFileToWord(this, "财务审计系统"); } /// <summary> /// 复制选中的数据到Excel /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void MicrosoftExcelToolStripMenuItem_Click(object sender, EventArgs e) { // throw new NotImplementedException(); HR.Control.DataGridViewOperation.Operate.OutputOperate outDgv = new HR.Control.DataGridViewOperation.Operate.OutputOperate(); outDgv.CopyToExcel(this, "DataGridView选中单元格导入到Excel练习"); } void 输出到Excel文件ToolStripMenuItem_Click(object sender, EventArgs e) { HR.Control.DataGridViewOperation.Operate.OutputOperate OO = new HR.Control.DataGridViewOperation.Operate.OutputOperate(); OO.OutputFileToExcel(this, System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\temp.xls", true); } void 另存为Excel文件_Click(object sender, EventArgs e) { if (this.RowCount==0||this.ColumnCount==0) { return; } SaveFileDialog SFD = new SaveFileDialog(); SFD.Filter = "Microsoft Excel电子文档(*.xls)|*.xls"; if (SFD.ShowDialog()==DialogResult.OK) { this.Cursor = Cursors.WaitCursor; //引用项目B组件 HR.Control.DataGridViewOperation.Operate.OutputOperate OO = new HR.Control.DataGridViewOperation.Operate.OutputOperate(); OO.OutputFileToExcel(this, SFD.FileName, false); GC.Collect(); this.Cursor = Cursors.Default; } } /// <summary> /// 复制选中单元格的数据 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void CopyData(object sender, EventArgs e) { if (this.Rows.Count==0 || this.Columns.Count==0) { return; } this.Focus(); int i = this.GetCellCount(DataGridViewElementStates.Selected); if (i>0) { Clipboard.SetDataObject(this.GetClipboardContent()); } } /// <summary> /// 降序操作 /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> /// <remarks></remarks> void DescOrderSort(object sender, EventArgs e) { if (this.Rows.Count==0 || this.Columns.Count==0) { return; } try { this.Cursor = Cursors.WaitCursor; this.Sort(this.CurrentCell.OwningColumn, System.ComponentModel.ListSortDirection.Descending); this.Cursor = Cursors.Default; } catch { } } /// <summary> ///升序操作 /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> /// <remarks></remarks> void AscendOrderSort(object sender, EventArgs e) { if (this.Rows.Count==0 || this.Columns.Count==0 ) { return; } try { this.Cursor = Cursors.WaitCursor; this.Sort(CurrentCell.OwningColumn, System.ComponentModel.ListSortDirection.Ascending); this.Cursor = Cursors.Default; } catch { } } /// <summary> /// 右键菜单弹出时所做的操作 /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.ComponentModel.CancelEventArgs"/> instance containing the event data.</param> /// <remarks></remarks> void contextMenu_Opening(object sender, System.ComponentModel.CancelEventArgs e) { try { if (this.AutoSizeColumnsMode == DataGridViewAutoSizeColumnsMode.AllCells) { this.自动列宽ToolStripMenuItem.Checked = true; } else { this.自动列宽ToolStripMenuItem.Checked = false; } if (this.SelectedCells.Count == 1) { this.锁定到此行ToolStripMenuItem.Enabled = true; this.锁定到此列ToolStripMenuItem.Enabled = true; if (!this.Rows[this.CurrentCell.RowIndex].Frozen) { this.锁定到此行ToolStripMenuItem.Enabled = true; } else { this.锁定到此行ToolStripMenuItem.Enabled = true; } if (!this.Columns[this.CurrentCell.ColumnIndex].Frozen) { this.锁定到此列ToolStripMenuItem.Enabled = true; } else { this.锁定到此列ToolStripMenuItem.Enabled = false; } } else { this.锁定到此行ToolStripMenuItem.Enabled = false; this.锁定到此列ToolStripMenuItem.Enabled = false; } } catch { } } /// <summary> /// 填充数据表控件时,设置各列是否允许排序 /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> /// <remarks></remarks> private void DataGridViewDataSourceChanged(object sender, EventArgs e) { try { for (int i = 0; i < this.Columns.Count; i++) { if (!this.HRColumnSort) { this.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable; } if (this.Columns[i].ValueType.ToString().ToLower() == "system.decimal") { this.Columns[i].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight; } if (this.Columns[i].ValueType.ToString().ToLower() == "int32") { this.Columns[i].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight; } if (this.Columns[i].ValueType.ToString().IndexOf("方向") > -1) { this.Columns[i].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter; ; } } } catch { } } #region DataGridView自定义属性 public int FormId { get { return formId; } set { formId = value; } } public bool HRColumnSort { get { return hRColumnSort; } set { hRColumnSort = value; if (hRColumnSort) { this.降序ToolStripMenuItem.Enabled = true; this.升序ToolStripMenuItem.Enabled = true; try { for (int i = 0; i < this.ColumnCount; i++) { this.Columns[i].SortMode = DataGridViewColumnSortMode.Automatic; } } catch { } } else { this.降序ToolStripMenuItem.Enabled = false; this.升序ToolStripMenuItem.Enabled = false; try { for (int i = 0; i < this.ColumnCount; i++) { this.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable; } } catch { } } } } #endregion } }
项目B
项目B在外面需要引用
Microsoft.Office.Interop.Excel
Microsoft.Office.Interop.Word
DataGridView导出Excel、Word、鼠标选定求和等扩展功能。
using System.Runtime.InteropServices; using System.Windows.Forms; using Microsoft.Office.Interop.Excel; using Microsoft.Office.Interop.Word; namespace HR.Control.DataGridViewOperation { public class Operate { /// <summary> /// DataGridView输出类操作 /// </summary> public class OutputOperate { //杀Excel后台进程 [DllImport("User32.dll", CharSet = CharSet.Auto)] public static extern int GetWindowThreadProcessId(IntPtr hwnd, out int Pid); /// <summary> /// DataGridView控件选中数据保存到Excel /// </summary> /// <param name="ExportDgv"></param> /// <param name="DgvTitle"></param> /// <returns></returns> public bool CopyToExcel(DataGridView ExportDgv, string DgvTitle) { try { if (ExportDgv == null) { return false; } if (ExportDgv.Columns.Count == 0 || ExportDgv.Rows.Count == 0) { return false; } //Excel2003最大行是65535 ,最大列是255 //Excel2007最大行是1048576,最大列是16384 //if (ExportDgv.RowCount > 65536 || ExportDgv.ColumnCount > 256) //{ // return false; //} ExportDgv.Focus(); //复制数据到Clipboard int I = ExportDgv.GetCellCount(DataGridViewElementStates.Selected); if (I > 0) { Clipboard.SetDataObject(ExportDgv.GetClipboardContent()); } //创建Excel对象 Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application(); if (xlApp == null) { return false; } //创建Excel工作薄 Microsoft.Office.Interop.Excel.Workbook xlBook = xlApp.Workbooks.Add(true); //创建Excel工作表 Microsoft.Office.Interop.Excel.Worksheet xlSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlBook.Worksheets[1];//第1个工作表 //粘贴数据 xlSheet.get_Range("A1", System.Type.Missing).PasteSpecial(XlPasteType.xlPasteAll, XlPasteSpecialOperation.xlPasteSpecialOperationNone, System.Type.Missing, System.Type.Missing); //显示工作薄区间 xlApp.Visible = true; xlApp.Caption = DgvTitle; //设置文本表格的属性 xlApp.Cells.EntireColumn.AutoFit();//自动列宽 xlApp.Cells.VerticalAlignment = Microsoft.Office.Interop.Excel.Constants.xlCenter; xlApp.Cells.HorizontalAlignment = Microsoft.Office.Interop.Excel.Constants.xlLeft; xlApp.ErrorCheckingOptions.BackgroundChecking = false; return true; } catch { return false; } } /// <summary> /// DataGridView中的所有数据导出到Excel /// </summary> /// <param name="ExportDgv">需要导出的DataGridView</param> /// <param name="fullFileName">导出后的文件全路径</param> /// <param name="isOpenFile">文件是否打开</param> /// <returns></returns> public bool OutputFileToExcel(DataGridView ExportDgv, string fullFileName, bool isOpenFile) { int id=0; bool ExportSuccess = false; int RowIndex = 0; int ColIndex = 0; //数据验证 if (ExportDgv==null) { return false; } if (ExportDgv.ColumnCount==0|| ExportDgv.RowCount==0) { return false; } if (ExportDgv.RowCount > 65536 || ExportDgv.ColumnCount > 256) { return false; } //有效的行数、列数 int rowCount = ExportDgv.Rows.GetRowCount(DataGridViewElementStates.Visible); int colCount = ExportDgv.Columns.GetColumnCount(DataGridViewElementStates.Visible); Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application(); if (xlApp == null) { return false; } //创建Excel工作薄 Microsoft.Office.Interop.Excel.Workbook xlBook = xlApp.Workbooks.Add(true); //创建Excel工作表 Microsoft.Office.Interop.Excel.Worksheet xlSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlBook.Worksheets[1];//第1个工作表 Microsoft.Office.Interop.Excel.Range range; IntPtr intp=new IntPtr(xlApp.Hwnd); //定义一个缓存,用来存放DataGridView的数据 object[,] objData = new object[rowCount + 1, colCount]; //1.存放DataGridView的列题行,隐藏列不要 for (int i = 0; i < ExportDgv.Columns.Count; i++) { if (ExportDgv.Columns[i].Visible) { objData[RowIndex, ColIndex++] = ExportDgv.Columns[i].HeaderText;//将列标题放入缓存中 //设置成文本型 if (ExportDgv.Columns[i].ValueType.ToString()=="System.String") { range = xlSheet.get_Range(xlApp.Cells[1, ColIndex], xlApp.Cells[rowCount + 1, ColIndex]); range.NumberFormat = "@"; } } } //2.存放DataGridView中的数据, for (int i = 1; i < rowCount; i++) { RowIndex++; ColIndex = 0; for (int j = 0; j < ExportDgv.Columns.Count; j++) { if (ExportDgv.Columns[j].Visible) { objData[RowIndex, ColIndex++] = ExportDgv[j, RowIndex - 1].Value; } } System.Windows.Forms.Application.DoEvents(); } //3.写入到Excel range = xlSheet.get_Range(xlApp.Cells[1, 1], xlApp.Cells[rowCount + 1, colCount]); range.Value2 = objData; //保存 try { //设置文本表格的属性 xlApp.Cells.EntireColumn.AutoFit();//自动列宽 xlApp.Cells.VerticalAlignment = Microsoft.Office.Interop.Excel.Constants.xlCenter; xlApp.Cells.HorizontalAlignment = Microsoft.Office.Interop.Excel.Constants.xlLeft; xlApp.ErrorCheckingOptions.BackgroundChecking = false; //设置列头 range = xlSheet.get_Range(xlApp.Cells[1, 1], xlApp.Cells[1, colCount]);//第一行数据,列标题 range.Font.Bold = true; range.HorizontalAlignment = Microsoft.Office.Interop.Excel.Constants.xlCenter; xlBook.Save(); xlBook.SaveCopyAs(fullFileName); ExportSuccess = true; } catch { ExportSuccess = false; } finally { //释放资源,关闭进程 xlApp.Quit(); GetWindowThreadProcessId(intp, out id); System.Diagnostics.Process P = System.Diagnostics.Process.GetProcessById(id); P.Kill(); } if (isOpenFile) //打开文件 { HR.Class.IO.FileOperat FP = new HR.Class.IO.FileOperat(); FP.OpenFile(fullFileName); } return ExportSuccess; } /// <summary> /// DataGridView中选中的数据复制到Word /// </summary> /// <param name="ExportDgv"></param> /// <param name="WordTitle"></param> /// <returns></returns> public bool OutputFileToWord(DataGridView ExportDgv, string WordTitle) { try { if (ExportDgv == null) { return false; } if (ExportDgv.Columns.Count == 0 || ExportDgv.Rows.Count == 0) { return false; } //复制数据到Clipboard int I = ExportDgv.GetCellCount(DataGridViewElementStates.Selected); if (I > 0) { //为了解决极少部分机器中文字符乱码问题 //一般为"区域选项,字符集设置不一样的问题 //Clipboard.SetDataObject(ExportGrid.GetClipboardContent()); Clipboard.SetText(ExportDgv.GetClipboardContent().GetData(DataFormats.Text).ToString()); } else { return false; } //创建Word对象 object iMissing = System.Type.Missing; Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application(); if (wordApp==null) { return false; } Microsoft.Office.Interop.Word.Document wordDoc = wordApp.Documents.Add(ref iMissing,ref iMissing,ref iMissing,ref iMissing); //粘贴数据 wordDoc.ActiveWindow.Selection.PasteSpecial(ref iMissing, ref iMissing, ref iMissing, ref iMissing, ref iMissing, ref iMissing, ref iMissing); wordApp.Caption = WordTitle; wordApp.Visible = true;//显示粘贴的数据 return true; } catch { return false; } } } /// <summary> /// DataGridView多选选中求和 /// </summary> public class MultiSelectSum { /// <summary> /// DataGridView选中的单元格求和 /// </summary> /// <param name="dgv"></param> /// <param name="toolTip"></param> public bool DataGridViewSelectCellsSum(DataGridView dgv, ToolTip toolTip) { //verify if (dgv.SelectedCells.Count < 2 ) { toolTip.RemoveAll(); return false; } //选中的单元格大于10000个或者DataGridView是全选 if (dgv.SelectedCells.Count > 10000 || dgv.SelectedCells.Count == dgv.GetCellCount(DataGridViewElementStates.None)) { toolTip.RemoveAll(); return false; } DataSet Ds = new DataSet(); System.Data.DataTable DGroup = new System.Data.DataTable("DGroup");// 存放列名 System.Data. DataTable Dt = new System.Data.DataTable("Dt");//存放列名和数值 ArrayList MaxNameLength=new ArrayList(); //保存列名的长度 ArrayList MaxValueLength=new ArrayList();//保存数值的长度 DGroup.Columns.Add("ColumnName", typeof(string)); Dt.Columns.Add("ColumnName", typeof(string)); Dt.Columns.Add("ColumnValue", typeof(decimal)); DataRow dr = null; //遍历选中单元格的值 foreach (DataGridViewCell cell in dgv.SelectedCells) { dr = Dt.NewRow(); if (cell.ValueType.Name.ToString().ToLower()=="decimal" || cell.ValueType.Name.ToString().ToLower()=="int32") { dr["ColumnName"] = dgv.Columns[cell.ColumnIndex].Name; if (cell.Value == null) { dr["ColumnValue"] = 0; } else { dr["ColumnValue"] = cell.Value.ToString(); MaxValueLength.Add(cell.Value.ToString().Length); } Dt.Rows.Add(dr); //判断将要添加进去的列值是否在DGroup中已存在 if (DGroup.Select("ColumnName='" + dgv.Columns[cell.ColumnIndex].Name + "'").Length == 0) { DataRow dr1 = DGroup.NewRow(); dr1["ColumnName"] = dgv.Columns[cell.ColumnIndex].Name; DGroup.Rows.Add(dr1); MaxNameLength.Add(dgv.Columns[cell.ColumnIndex].Name.Length); } } } Ds.Tables.Add(DGroup); Ds.Tables.Add(Dt); DataRelation dRelation = new DataRelation("dataRel", Ds.Tables["DGroup"].Columns["ColumnName"], Ds.Tables["Dt"].Columns["ColumnName"]); Ds.Relations.Add(dRelation); DGroup.Columns.Add("ColumnSum").Expression = "sum(child(dataRel).ColumnValue)";//添加一个总计列,并对各列求值 string desSum = Dt.Compute("sum(ColumnValue)", "").ToString();//求Dt表ColumnValue列的总计 MaxNameLength.Add("总合计:".Length); MaxValueLength.Add(desSum.Length); DGroup.AcceptChanges();//提交对DGroup表的修改 MaxNameLength.Sort(); MaxValueLength.Sort(); int MaxNameLen; //保存最大列名长度 int MaxValueLen;//保存最大数值长度 MaxNameLen = Convert.ToInt32(MaxNameLength[MaxNameLength.Count - 1]); MaxValueLen = Convert.ToInt32(MaxValueLength[MaxValueLength.Count - 1]); string title = "";//提示信息 for (int i = 0; i < DGroup.Rows.Count; i++) { string strOneLine = ""; strOneLine = (DGroup.Rows[i]["ColumnName"].ToString()+":").PadRight(MaxNameLen + 1, ' '); strOneLine = strOneLine + (DGroup.Rows[i]["ColumnSum"].ToString()).PadLeft(MaxValueLen, ' '); title = title + strOneLine + System.Environment.NewLine;//换行 } title = title + "总合计:".PadRight(MaxNameLen + 1, ' ') + desSum.PadLeft(MaxNameLen + 1, ' '); dgv.ShowCellToolTips = false; toolTip.ToolTipIcon = ToolTipIcon.Info; toolTip.ToolTipTitle = "鼠标选定合计信息:"; toolTip.IsBalloon = true;//气球形状 toolTip.UseAnimation = true; toolTip.AutoPopDelay = 10000; toolTip.RemoveAll(); toolTip.SetToolTip(dgv,title ); DGroup.Dispose(); Dt.Dispose(); GC.Collect(); return true; } } } }
发表评论
-
C# 实现将文件夹分卷压缩
2015-04-17 17:01 1241http://bbs.csdn.net/topics/3907 ... -
C#发送邮件
2015-04-17 15:58 696public class SendEmailHelper ... -
C# xml文件读取
2015-02-11 16:08 648看附件................ -
什么时候该用委托,为什么要用委托,委托有什么好处....
2015-01-29 16:56 818http://www.cnblogs.com/superpce ... -
C#中动态加载和卸载DLL
2015-01-26 14:02 1425在C++中加载和卸载DLL是一件很容易的事,LoadLibra ... -
转:c#常用的18种设计模式
2015-01-21 08:16 777http://blog.jobbole.com/78130/ -
C#委托的介绍(delegate、Action、Func、predicate)
2015-01-09 17:26 1132http://www.cnblogs.com/akwwl/p/ ... -
接口和抽象类有什么区别 .
2014-12-22 16:35 617接口和抽象类有什么区别 你选择使用接口和抽象类的依据是什么 ... -
C#一个简单写日志文件的类
2014-12-11 09:57 1112/// <summary> /// L ... -
Linq初级班 Linq to DataSet体验(单表、多表联合查询JOIN语法)
2014-12-10 14:34 355http://www.cnblogs.com/huangcon ... -
C#泛型详解
2014-11-29 11:31 482我们在编写程序时,经常遇到两个模块的功能非常相似,只是一个是处 ... -
线程同步与异步的区别
2014-11-26 09:12 883异步处理就是按照不同步的程序处理问题。异步处理与同步处理是对立 ... -
应用C#和SQLCLR编写SQL Server用户定义函数 .
2013-10-09 17:07 485http://blog.csdn.net/zhzuo/arti ... -
log4Net简介
2013-06-30 11:32 575使用log4Net可以将系统听日志保存到DB、日志文件、邮箱中 ... -
DataGridView历史记录的前进与后退操作
2013-06-23 11:13 1108此功能介绍:DataGridView频繁查询数据时,可以将每次 ... -
c# 对INI配置文件的读取操作
2013-06-17 10:51 678此种方法只对如下格式的INI文件起作用 server=loca ... -
对集合控件(ListBox,ComboBox,TreeView,RichTextBox,DataGridView)的查找、替换操作控件
2013-06-15 09:39 1549一、程序入口: using System; using ... -
C#对文件、文件夹操作公用组件
2013-06-11 09:46 968namespace HR.Class.IO { / ... -
TreeView控件操作开发篇之(五)
2013-06-09 00:09 828#region 加载文件夹及文件到树 ... -
TreeView控件操作开发篇之(五)
2013-06-08 23:14 2#region "查找遍历树节点" ...
相关推荐
在.NET框架中,DataGridView控件是一个非常重要的组件,主要用于显示和操作数据表格。它提供了丰富的功能,包括数据的浏览、编辑、排序、过滤等。在VB.NET和C#等.NET语言中,使用DataGridView控件可以方便地构建用户...
这个压缩包"DataGridView功能扩展及其它控件源码"包含了一些高级特性的实现,旨在增强标准的DataGridView控件的功能,同时也涉及到MonthCalendar和GridCalendar这两个日历控件的扩展。让我们详细探讨这些扩展功能...
在.NET框架中,DataGridView控件是一个非常重要的组件,它用于显示和编辑表格数据。这篇文章将深入探讨这个控件的一些高级特性和用法,帮助开发者更好地理解和应用它。 1. 数据绑定:DataGridView控件可以轻松地与...
这个主题,"DataGridView控件的简单扩展",聚焦于如何通过编程方式增强`DataGridView`的功能,特别是让某个字段自动充满整个列宽,从而提供更好的用户界面体验。 在Windows Forms开发中,`DataGridView`控件的默认...
"可折叠datagridview控件"是指通过自定义扩展或第三方库实现的,能够在数据显示时进行折叠和展开操作的特殊版本。这种控件能够帮助用户更有效地管理和查看大量数据,尤其是在数据层级关系复杂的情况下。 首先,我们...
在.NET框架中,C#的DataGridView控件是一个强大的数据展示工具,它允许用户在Windows Forms应用程序中以表格形式查看和编辑数据。...在实际开发中,可以根据需求进一步扩展功能,例如添加排序、过滤、分页等特性。
### 控件代码C#通过修改DataGridView控件来修改Access数据 #### 概述 本篇文章主要介绍了如何在C#应用程序中使用DataGridView控件与Microsoft ...在未来开发过程中,可以根据实际需求对这些基本功能进行扩展和优化。
我们需要扩展`DataGridView`的功能,添加对树形结构的支持。这可以通过监听`CellClick`事件,根据用户点击的行来展开或折叠相应的节点。同时,需要在`DataGridView`中添加额外的列来显示节点的展开/折叠状态。 3. ...
通过对这些代码的学习和研究,开发者可以了解到如何扩展.NET Framework的内置控件,以满足特定的应用场景需求。这不仅有助于提升个人技能,也为开发高效、易用的Windows应用程序提供了新的思路。 总之,这个自定义...
在C#编程中,`dataGridView`控件是...这需要对`dataGridView`的特性和事件机制有深入理解,同时也需要掌握基本的条件判断和数据处理技巧。在实际开发中,这些知识可以用于创建更加灵活和用户友好的数据展示界面。
在某些复杂的应用场景中,我们可能需要实现数据的分层显示,这时就需要用到“可折叠的DataGridView控件”。本文将详细讲解如何在C# WinForm环境下实现这个功能。 首先,我们要理解`DataGridView`的基本使用。`...
在Windows桌面应用中,数据展示是常见的需求,而DataGridView控件是C#中用于展示大量结构化数据的强大工具。本篇将详细介绍"C# Datagridview 分页控件以及测试程序"的相关知识点,并提供实现分页功能的思路。 1. ...
在.NET框架中,Windows Forms应用程序开发中经常使用DataGridView控件来展示数据表格。为了提高用户体验,我们有时需要在某些单元格内添加下拉列表功能,让用户能够从预定义的选项中选择,而不是直接输入。本篇文章...
标题中的“一个很好的DataGridView控件Dll(C#)”指的是一个用C#编程语言编写的,专门针对Windows Forms应用程序的自定义DataGridView控件库。这个控件库可能包含了一些增强功能或者特定的定制,以便更好地适应项目...
此外,如果`AX.SubDataGrid.dll`库提供了丰富的数据处理功能,还可以考虑利用这些功能扩展`DataGridView`的其他高级特性,比如自定义汇总、动态计算等。 综上所述,本实例主要涉及到`C#`中`Windows Forms`应用下的`...
在.NET Framework的Windows Forms开发环境中,`DataGridView`控件是一个常用的数据展示组件,它允许用户以表格形式查看和编辑数据。然而,标准的`DataGridView`控件并不直接支持分页功能,开发者通常需要通过自定义...
"DataGridview扩展控件"就是这样一个工具,它不仅保留了原生`DataGridView`的基本特性,还添加了一系列高级功能,旨在提升开发效率并提供更好的用户体验。 1. **数据操作**: - 增加:扩展控件允许用户直接在界面...
在探讨"C# Datagridview读扩展类"这一主题时,我们深入分析了如何利用C#中的Datagridview组件以及自定义的扩展类来增强数据展示和处理能力。Datagridview是Windows Forms应用程序中一个非常强大的控件,用于显示、...
在.NET开发环境中,经常需要处理数据的导入导出操作,其中一种常见的需求是将Excel数据导入到Windows Forms或ASP.NET应用程序中的datagridview控件。datagridview控件是一种用于展示表格数据的强大工具,它可以方便...