C# DataGridView 数据导出Excel 操作源码

private void ExportToExcel()
        {
            if (dgv_Export.Rows.Count <= 0) return;

            #region   验证可操作性

            //声明保存对话框
            SaveFileDialog dlg = new SaveFileDialog();
            //默认文件后缀
            dlg.DefaultExt = "xls";
            //文件后缀列表
            dlg.Filter = "EXCEL文件(*.xls)|*.xls";
            //默认文件名称
            dlg.FileName = "aaaa";
            //默然路径是系统当前路径
            dlg.InitialDirectory = Directory.GetCurrentDirectory();
            //打开保存对话框
            if (dlg.ShowDialog() == DialogResult.Cancel) return;
            //返回文件路径
            string fileNameString = dlg.FileName;
            //验证strFileName是否为空或值无效
            if (fileNameString.Trim() == "") return;
            //定义表格内数据的行数和列数
            int rowscount = dgv_Export.Rows.Count;
            int colscount = dgv_Export.Columns.Count;
            //行数必须大于0
            if (rowscount <= 0)
            {
                MessageBox.Show("没有数据可供保存", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            //列数必须大于0
            if (colscount <= 0)
            {
                MessageBox.Show("没有数据可供保存", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            //行数不可以大于65536
            if (rowscount > 65536)
            {
                MessageBox.Show("数据记录数太多(最多不能超过65536条),不能保存", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            //列数不可以大于255
            if (colscount > 255)
            {
                MessageBox.Show("数据记录行数太多,不能保存", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            //验证以fileNameString命名的文件是否存在,如果存在删除它
            FileInfo file = new FileInfo(fileNameString);
            if (file.Exists)
            {
                try
                {
                    file.Delete();
                }
                catch (Exception error)
                {
                    MessageBox.Show(error.Message, "删除失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
            }
            #endregion

            Microsoft.Office.Interop.Excel.Application objExcel = null;
            Microsoft.Office.Interop.Excel.Workbook objWorkbook = null;
            Microsoft.Office.Interop.Excel.Worksheet objsheet = null;

            ProgressBar tempProgressBar = new ProgressBar();
            try
            {
                //声明对象
                objExcel = new Microsoft.Office.Interop.Excel.Application();
                objWorkbook = objExcel.Workbooks.Add(Missing.Value);
                objsheet = (Microsoft.Office.Interop.Excel.Worksheet)objWorkbook.ActiveSheet;

                //设置Excel不可见
                objExcel.Visible = false;
                //Excel当前行
                int ExcelRow = 1;
                //Excel当前列
                int ExcelCol = 0;
                //向Excel中写入表格的表头
                for (int i = 0; i < dgv_Export.ColumnCount; i++)
                {
                    if (dgv_Export.Columns[i].Visible == true)
                    {
                        ExcelCol++;
                    }
                }

                Microsoft.Office.Interop.Excel.Range sheetRange;

                #region "标题写入"
                if (txt_HeaderM.Text.Trim() != "")
                {
                    //全并标题行
                    sheetRange = objsheet.get_Range(objsheet.Cells[ExcelRow, 1], objsheet.Cells[ExcelRow, ExcelCol]);
                    sheetRange.Merge(0);
                    //写入主标题
                    sheetRange.Cells[ExcelRow, 1] = txt_HeaderM.Text.Trim();
                    //对齐方式居中
                    sheetRange.HorizontalAlignment = 3;
                    //字体样式
                    sheetRange.Font.Bold = true;
                    //字体大小
                    sheetRange.Font.Size = 14;
                    sheetRange.BorderAround(XlLineStyle.xlContinuous, XlBorderWeight.xlMedium, XlColorIndex.xlColorIndexAutomatic, System.Drawing.Color.PeachPuff.ToArgb());
                    ExcelRow++;
                }

                if (txt_HeaderS.Text.Trim() != "")
                {
                    //全并标题行
                    sheetRange = objsheet.get_Range(objsheet.Cells[ExcelRow, 1], objsheet.Cells[ExcelRow, ExcelCol]);
                    sheetRange.Merge(true);
                    //写入次标题
                    objsheet.Cells[ExcelRow, 1] = txt_HeaderS.Text.Trim();
                    //对齐方式居中
                    sheetRange.HorizontalAlignment = 3;

                    ExcelRow++;
                }
                #endregion

                //向Excel中写入表格的表头
                ExcelCol = 1;
                for (int i = 0; i < dgv_Export.ColumnCount; i++)
                {
                    if (dgv_Export.Columns[i].Visible == true)
                    {
                        sheetRange = objsheet.get_Range(objsheet.Cells[ExcelRow, ExcelCol], objsheet.Cells[ExcelRow, ExcelCol]);
                        objsheet.Cells[ExcelRow, ExcelCol] = dgv_Export.Columns[i].HeaderText.Trim();
                        sheetRange.Font.Bold = true;
                        sheetRange.HorizontalAlignment = 3;
                        sheetRange.Borders.LineStyle = XlLineStyle.xlContinuous;//设置边框线型
                        ExcelCol++;
                    }
                }
                ExcelRow++;

                #region "添加并设置进度条"
                p_Grid.Controls.Add(tempProgressBar);
                p_Grid.Controls.SetChildIndex(tempProgressBar, 0);
                tempProgressBar.Width = tempProgressBar.Parent.Width / 2;
                tempProgressBar.Top = (tempProgressBar.Parent.Height - tempProgressBar.Height) / 2;
                tempProgressBar.Left = (tempProgressBar.Parent.Width - tempProgressBar.Width) / 2;

                tempProgressBar.Refresh();
                tempProgressBar.Visible = true;
                tempProgressBar.Minimum = 1;
                tempProgressBar.Maximum = dgv_Export.RowCount;
                tempProgressBar.Step = 1;
                #endregion
                //向Excel中逐行逐列写入表格中的数据
                for (int row = 0; row < dgv_Export.RowCount; row++)
                {
                    tempProgressBar.PerformStep();

                    ExcelCol = 1;
                    for (int col = 0; col < colscount; col++)
                    {
                        if (dgv_Export.Columns[col].Visible == true)
                        {
                            sheetRange = objsheet.get_Range(objsheet.Cells[ExcelRow, ExcelCol], objsheet.Cells[ExcelRow, ExcelCol]);
                            sheetRange.Interior.Color=System.Drawing.Color.Pink.ToArgb();//设置背景色
                            sheetRange.Font.Color =System.Drawing.Color.Red.ToArgb();//设置字体颜色
                            sheetRange.Borders.LineStyle = XlLineStyle.xlDashDot;//设置边框线型
                            //sheetRange.Borders.get_Item(XlBordersIndex.xlEdgeTop).LineStyle = XlLineStyle.xlContinuous;//设置边框单边线型

                            //写入单元格
                            objsheet.Cells[ExcelRow, ExcelCol] = dgv_Export.Rows[row].Cells[col].Value.ToString().Trim();
                            //行高
                            sheetRange.RowHeight = dgv_Export.Rows[row].Height * RowHeightRate;
                            //列宽
                            sheetRange.ColumnWidth = dgv_Export.Columns[col].Width * 0.13;
                            //单元格对齐方式
                            int Excel_Alignment = 2;
                            if (dgv_Export.Columns[col].DefaultCellStyle.Alignment.ToString().IndexOf("Center") > 0)
                            {
                                Excel_Alignment = 3;
                            }
                            else if (dgv_Export.Columns[col].DefaultCellStyle.Alignment.ToString().IndexOf("Right") > 0)
                            {
                                Excel_Alignment = 4;
                            }
                            sheetRange.HorizontalAlignment = Excel_Alignment;
                            ExcelCol++;
                        }
                    }
                    ExcelRow++;
                }
                //移除进度条
                tempProgressBar.Parent.Controls.Remove(tempProgressBar);


                //保存文件
                objWorkbook.SaveAs(fileNameString, Missing.Value, Missing.Value, Missing.Value, Missing.Value,
                            Missing.Value, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlShared, Missing.Value, Missing.Value, Missing.Value,
                            Missing.Value, Missing.Value);
            }
            catch (Exception error)
            {
                //移除进度条
                tempProgressBar.Parent.Controls.Remove(tempProgressBar);
                MessageBox.Show(error.Message, "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            //如果要显示结果就显示Excel并返回,否则就退出Excel;
            if (chb_View.Checked) { objExcel.Visible = true; return; }
            //关闭Excel应用
            if (objWorkbook != null) objWorkbook.Close(Missing.Value, Missing.Value, Missing.Value);
            if (objExcel.Workbooks != null) objExcel.Workbooks.Close();
            if (objExcel != null) objExcel.Quit();

            objsheet = null;
            objWorkbook = null;
            objExcel = null;
            MessageBox.Show(fileNameString + "导出完毕!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值