DataGridView 导出数据到Exexl中

做开发时,积累很重要,每天总是写同样的东西会很烦人的事,所以有空的时候花一点时间来整理代码。

  public class ExcelImport
     {
        Thread thread = null;
        /// <summary>
        /// 此用于生成Excel
        /// </summary>
        public ExcelImport()
        { 
           thread=new Thread(new ThreadStart(createExcel));
        }

        #region  生成Execl,此方法运用线程生成
        private DataGridView  dgv { get; set; }
        private string filePath { get; set; }
        private List<string> columnsName { get; set; }
        private int columnsColor { get; set; }
        private int oddColor { get; set; }
        private int evenColor { get; set; }
        /// <summary>
        /// 生成Execl,此方法运用线程生成
        /// </summary>
        /// <param name="dgv">DataGridView对象</param>
        /// <param name="filePath">保存文件路径</param>
        /// <param name="columnsName">不要显示DataGridView列名</param>
        /// <param name="columnsColor">生成Cxecl列名的背景颜色</param>
        /// <param name="oddColor">奇数行的背景颜色</param>
        /// <param name="evenColor">偶数行的背景颜色</param>
        public  void ImportExeclFile(DataGridView dgv, string filePath, List<string> columnsName, int columnsColor, int oddColor, int evenColor)
        {
            this.dgv = dgv;
            this.filePath = filePath;
            this.columnsName = columnsName;
            this.columnsColor = columnsColor;
            this.oddColor = oddColor;
            this.evenColor = evenColor;
            thread.Start();
        }
        /// <summary>
        /// 生成Excel
        /// </summary>
        private void createExcel()
        { 
        
            #region  新增一个工作表
            System.Reflection.Missing miss = System.Reflection.Missing.Value;
            Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.ApplicationClass();
            if (excel == null)
                throw new Exception("Excel无法启动!");
            Microsoft.Office.Interop.Excel.Workbook xlbook = excel.Workbooks.Add(true);//新增一个工作表
            Microsoft.Office.Interop.Excel.Workbooks books = (Microsoft.Office.Interop.Excel.Workbooks)excel.Workbooks;
            Microsoft.Office.Interop.Excel.Workbook book = (Microsoft.Office.Interop.Excel.Workbook)(books.Add(miss));
            Microsoft.Office.Interop.Excel.Worksheet sheet = (Microsoft.Office.Interop.Excel.Worksheet)book.ActiveSheet;
            excel.Visible = false;//不可见Execl

            #endregion

            #region 整工作薄样式
            excel.Cells.HorizontalAlignment = Microsoft.Office.Interop.Excel.Constants.xlLeft;
            excel.Cells.RowHeight = 25;
            excel.Cells.ColumnWidth = 20;
            #endregion

            #region Excel第一行的样式
            Microsoft.Office.Interop.Excel.Range range = excel.get_Range(excel.Cells[1, 1], excel.Cells[1, dgv.Columns.Count-columnsName.Count]);
            range.Font.Bold = true;
            range.Font.Size = 15;
            range.Interior.ColorIndex = columnsColor;
            #endregion

            #region 隔行样式
            for (int i = 2; i <=dgv.Rows.Count+1; i++)
            {
                Microsoft.Office.Interop.Excel.Range rowcolor = excel.get_Range(excel.Cells[i, 1], excel.Cells[i, dgv.Columns.Count-columnsName.Count]);
                if (i % 2 == 1)//样式变化
                {

                    rowcolor.Interior.ColorIndex = oddColor;
                }
                if (i % 2 == 0)//样式变化
                {
                    rowcolor.Interior.ColorIndex = evenColor;
                }
            }
            #endregion

            #region DatagridView 标题处理
            int columnindex = 1;
            for (int i = 0; i < dgv.ColumnCount; i++)
            {
                if (columnsName.Contains(dgv.Columns[i].HeaderText)) continue;
                excel.Cells[1, columnindex] = dgv.Columns[i].HeaderText;
                columnindex++;
            }
            #endregion

            #region Datagridview 处理显示中所有数据
            int improtDatacount = 0;
            for (int i = 0; i < dgv.Rows.Count; i++)
            {   
                int dataIndex = 1;
                for (int j = 1; j < dgv.ColumnCount; j++)
                {
                    if (columnsName.Contains(dgv.Columns[j].HeaderText)) continue;
                    excel.Cells[i + 2, dataIndex] = dgv.Rows[i].Cells[j].Value.ToString();
                    dataIndex++;
                   
                }
                improtDatacount++;

            }
            #endregion

            #region 保存一个工作表
            excel.DisplayAlerts = false;//设置禁止弹保存和覆盖的询问
            excel.AlertBeforeOverwriting = false;//设置禁止弹保存和覆盖的询问
            book.Saved = true;//
            //保存execl
            sheet.SaveAs(filePath, miss, miss, miss, miss, miss, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, miss, miss, miss);

            book.Close(false, miss, miss);
            books.Close();
            //关闭execl
            excel.Quit();
            System.Runtime.InteropServices.Marshal.ReleaseComObject(sheet);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(book);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(books);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
            GC.Collect();
            MessageBox.Show("成功导出" + improtDatacount + "条数据", "系统提醒");
            thread.Abort();
            #endregion

        }
        #endregion
View Code

 

        SaveFileDialog savefile = new SaveFileDialog();
            savefile.Filter = "Execl文件(*.xls)|*.xls";
            if (savefile.ShowDialog() == DialogResult.Cancel) return;
            List<string> columnnames=new List<string>();
            columnnames.Add("ID");
            columnnames.Add("Sex");
            ExcelImport em = new ExcelImport();
            em.ImportExeclFile(dataGridView1,savefile.FileName,columnnames,15,19,24);
View Code

 

posted @ 2013-06-11 13:06  Blue_Dream  阅读(188)  评论(0编辑  收藏  举报