c#中导出DataGridView数据至Excel文件

C# 专栏收录该内容
3 篇文章 0 订阅

1.添加引用
在这里插入图片描述
2.修改引用属性中【嵌入互操作类型】为false
在这里插入图片描述
3.新建class

public class ExportDGVToExcel
    {
        /// <summary>
        /// DataGridView导出到Excel
        /// </summary>
        /// <param name="strCaption">Excel文件中的标题
        /// <param name="myDGV">DataGridView 控件
        /// <returns>0:成功;1:DataGridView中无记录;2:Excel无法启动;100:Cancel;9999:异常错误</returns>
        public int ExportExcel(string strCaption, DataGridView myDGV, SaveFileDialog saveFileDialog,string fileName)
        {
            saveFileDialog.Filter = "Execl files (*.xlsx)|*.xlsx";
            saveFileDialog.FilterIndex = 0;
            saveFileDialog.RestoreDirectory = true;
            saveFileDialog.Title = "Export Excel File";
            saveFileDialog.FileName = fileName;
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                if (saveFileDialog.FileName == "")
                {
                    MessageBox.Show("请输入保存文件名!");
                    saveFileDialog.ShowDialog();
                }
                // 列索引,行索引,总列数,总行数
                int ColIndex = 0;
                int RowIndex = 0;
                int ColCount = myDGV.ColumnCount;
                int RowCount = myDGV.RowCount;
                if (myDGV.RowCount == 0)
                {
                    return 1;
                }
                // 创建Excel对象
                Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.ApplicationClass(); ;
                if (xlApp == null)
                {
                    return 2;
                }
                try
                {
                    // 创建Excel工作薄
                    Workbook xlBook = xlApp.Workbooks.Add(true);
                    Worksheet xlSheet = (Worksheet)xlBook.Worksheets[1];
                    // 设置标题,标题所占的单元格数与DataGridView中的列数相同
                    Range range = xlSheet.get_Range(xlApp.Cells[1, 1], xlApp.Cells[1, ColCount]);
                    //range.MergeCells = true;
                    xlApp.ActiveCell.FormulaR1C1 = strCaption;
                    xlApp.ActiveCell.Font.Size = 10;
                    xlApp.ActiveCell.Font.Bold = true;
                    xlApp.ActiveCell.HorizontalAlignment = Constants.xlCenter;
                    // 创建缓存数据
                    object[,] objData = new object[RowCount + 1, ColCount];
                    //获取列标题
                    foreach (DataGridViewColumn col in myDGV.Columns)
                    {
                        objData[RowIndex, ColIndex++] = col.HeaderText;
                    }
                    // 获取数据
                    for (RowIndex = 1; RowIndex <= RowCount; RowIndex++)
                    {
                        for (ColIndex = 0; ColIndex < ColCount; ColIndex++)
                        {
                            //验证DataGridView单元格中的类型,如果是string或是DataTime类型,则在放入缓存时在该内容前加入" ";
                            if (myDGV[ColIndex, RowIndex - 1].ValueType == typeof(string)
                                || myDGV[ColIndex, RowIndex - 1].ValueType == typeof(DateTime))
                            {
                                objData[RowIndex, ColIndex] = "";
                                if (myDGV[ColIndex, RowIndex - 1].Value != null)
                                {
                                    objData[RowIndex, ColIndex] = "" + myDGV[ColIndex, RowIndex - 1].Value.ToString();
                                }
                            }
                            else
                            {
                                objData[RowIndex, ColIndex] = myDGV[ColIndex, RowIndex - 1].Value;
                            }
                        }
                        System.Windows.Forms.Application.DoEvents();
                    }
                    // 写入Excel(xlApp.Cells[RowCount+1, ColCount]);)
                    range = xlSheet.get_Range(xlApp.Cells[1, 1], xlApp.Cells[RowCount + 1, ColCount]);
                    //添加一个格式声明,使得导出数据为10进制,非科学记数法。
                    range.NumberFormatLocal = "@";
                    range.Value2 = objData;
                    range.Columns.EntireColumn.AutoFit();//列宽自适应
                    xlBook.Saved = true;
                    xlBook.SaveAs(saveFileDialog.FileName);
                }
                catch (Exception err)
                {
                    MessageBox.Show("Err:" + err.Message);
                    return 9999;
                }
                finally
                {
                    xlApp.Quit();
                    GC.Collect(); //强制回收
                }
                return 0;
            }
            return 100;
        }
    }

4.调用class

private void button_Click(object sender, EventArgs e)
        {
            if (dataGridView1.Rows.Count == 0)
            {
                MessageBox.Show("无数据,请先检索!");
            }
            else {
                SaveFileDialog dialog = new SaveFileDialog();
                ExportDGVToExcel exportDataToExcel = new ExportDGVToExcel();
                int ret = exportDataToExcel.ExportExcel("数据汇总", dataGridView1, dialog, "效率管理" + DateTime.Now.ToString("yyyyMMddhhmmss"));
                if (ret == 0)
                {
                    MessageBox.Show("导出数据成功");
                }
                else if (ret != 100)
                {
                    MessageBox.Show("导出数据失败");
                }
            }
        }
  • 0
    点赞
  • 0
    评论
  • 0
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

©️2021 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值