对DataGridView控件的扩展开发

首先在项目中引用
    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;
               
            }
            
        }
}
}

你可能感兴趣的:(datagridview)