DataGridView扩展方法行号、全选、导出到Excel(引用excel组件、生成html两种方式)

 /// <summary>
        /// DataGridView添加行号
        /// </summary>
        /// <param name="dgv">DataGridView控件ID</param>
        public static void AddRowIndex(this DataGridView dgv)
        {
            dgv.RowPostPaint += delegate(object sender, DataGridViewRowPostPaintEventArgs e)
            {
                SolidBrush b = new SolidBrush(dgv.RowHeadersDefaultCellStyle.ForeColor);
                e.Graphics.DrawString((e.RowIndex + 1).ToString(), dgv.DefaultCellStyle.Font, b, e.RowBounds.Location.X + 10, e.RowBounds.Location.Y + 4);
            };
        }
        /// <summary>
        /// DataGridView添加全选
        /// </summary>
        /// <param name="dgv">DataGridView控件ID</param>
        /// <param name="columnIndex">全选所在列序号</param>
        public static void AddFullSelect(this DataGridView dgv, int columnIndex)
        {
            if (dgv.Rows.Count < 1)
            {
                return;
            }
            CheckBox ckBox = new CheckBox();
            Rectangle rect = dgv.GetCellDisplayRectangle(1, -1, true);
            ckBox.Size = new Size(dgv.Columns[1].Width - 12, 12); //大小               
            Point point = new Point(rect.X + 10, rect.Y + 3);//位置
            ckBox.Location = point;
            ckBox.CheckedChanged += delegate(object sender, EventArgs e)
            {
                for (int i = 0; i < dgv.Rows.Count; i++)
                {
                    dgv.Rows[i].Cells[columnIndex].Value = ((CheckBox)sender).Checked;
                }
                dgv.EndEdit();
            };
            dgv.Controls.Add(ckBox);
        }
       /// <summary>
        /// 导出到Excel(通过引用excel组件导出)
        /// </summary>
        /// <param name="dgv">DataGridView控件ID</param>
        public static void ExportExcel(this DataGridView dgv)
        {            
            if (dgv.Rows.Count == 0)
                return;
            //实例化一个Excel.Application对象  
            Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
            try
            {
                //让后台执行设置为不可见,为true的话会看到打开一个Excel,然后数据在往里写  
                excel.Visible = false;
                //设置禁止弹出保存和覆盖的询问提示框  
                excel.DisplayAlerts = false;
                excel.AlertBeforeOverwriting = false;

                //新增加一个工作簿,Workbook是直接保存,不会弹出保存对话框,加上Application会弹出保存对话框,值为false会报错  
                excel.Application.Workbooks.Add(true);
                //生成Excel中列头名称  
                for (int i = 0; i < dgv.Columns.Count; i++)
                {
                    excel.Cells[1, i + 1] = dgv.Columns[i].HeaderText;
                }
                //把DataGridView当前页的数据保存在Excel中  
                for (int i = 0; i < dgv.Rows.Count; i++)
                {
                    for (int j = 0; j < dgv.Columns.Count; j++)
                    {
                        if (dgv[j, i].ValueType == typeof(string))
                        {
                            excel.Cells[i + 2, j + 1] = "'" + dgv[j, i].Value.ToString();
                        }
                        else
                        {
                            excel.Cells[i + 2, j + 1] = dgv[j, i].Value.ToString();
                        }
                    }
                }
              //保存excel文件  
                excel.Save(System.AppDomain.CurrentDomain.BaseDirectory + "temp.xls");
            }
            catch 
            {                
            }
            finally
            {             
                excel.Quit();
                System.Runtime.InteropServices.Marshal.FinalReleaseComObject(excel);
                excel = null;
                GC.Collect();
            }
        }




       /// <summary>
        /// 导出到Excel(通过生成html导出)
        /// </summary>
        /// <param name="dgv">DataGridView控件ID</param>
       public static void ExportExcel(this DataGridView dgv)
        {
            if (dgv.Rows.Count == 0)
                return;

            const string HEADER = "<html xmlns:x=\"urn:schemas-microsoft-com:office:excel\">" +
                                          "<meta http-equiv=Content-Type content=\"text/html; charset=\"gb2312\">" +
                                          "<head>" +
                                          "<!--[if gte mso 9]><xml>" +
                                           "<x:ExcelWorkbook>" +
                                               "<x:ExcelWorksheets>" +
                                                   "<x:ExcelWorksheet>" +
                                                       "<x:Name>工作表标题</x:Name>" +
                                                       "<x:WorksheetOptions>" +
                                                           "<x:Print>" +
                                                               "<x:ValidPrinterInfo />" +
                                                           "</x:Print>" +
                                                       "</x:WorksheetOptions>" +
                                                   "</x:ExcelWorksheet>" +
                                               "</x:ExcelWorksheets>" +
                                           "</x:ExcelWorkbook>" +
                                       "</xml>" +
                                       "<![endif]-->";

            const string STYLE = "<style type=\"text/css\">" +
                                       ".text" +
                                       " {" +
                                       "   vnd.ms-excel.numberformat:@;" +
                                       " }" +                                     
                                       "</style>";

            using(SaveFileDialog saveFileDialog = new SaveFileDialog())
            {
                saveFileDialog.Title = "导出Excel文件到";
                saveFileDialog.Filter = "Execl files(*.xls)|All Files(*.*)";
                saveFileDialog.FileName = DateTime.Now.ToString("yyyyMMdd_HHmmss") + ".xls";
                saveFileDialog.AddExtension = true;
                saveFileDialog.RestoreDirectory = true;                 
                if (saveFileDialog.ShowDialog() == DialogResult.OK)
                {
                    using (StreamWriter writer = new StreamWriter(saveFileDialog.FileName, false, System.Text.Encoding.GetEncoding("gb2312"), 1024))
                    {
                        writer.WriteLine(HEADER);
                        writer.WriteLine(STYLE);
                        writer.WriteLine("</head><body><table border=\"1\" style=\"font-size:9pt\"><tr>");

                        for (int i = 0; i < dgv.Columns.Count; i++)
                        {
                            writer.WriteLine(string.Format("<th>{0}</th>", dgv.Columns[i].HeaderText));
                        }

                        for (int i = 0; i < dgv.Rows.Count; i++)
                        {
                            writer.WriteLine("<tr>");
                            for (int j = 0; j < dgv.Columns.Count; j++)
                            {
                                writer.WriteLine(string.Format("<td class=\"text\">{0}</td>", dgv[j, i].Value.ToString()));
                            }
                            writer.WriteLine("</tr>");
                        }
                        writer.WriteLine("</table></body>");
                    }
                }
            }   
        }
原文地址:https://www.cnblogs.com/gdjlc/p/2833850.html