EPPlus助力:优雅实现Excel数据到数据库的自动迁移之旅

这里我使用了Access数据库为例,导入EPPlus如果不会请看上一篇帖子

1.首先先设置EPPlus为非商业使用

cs 复制代码
  public Homes()
  {
      InitializeComponent();

      ExcelPackage.LicenseContext = OfficeOpenXml.LicenseContext.NonCommercial; // 设置EPPlus为非商业使用
  } 

2.Access数据库连接方法

cs 复制代码
 #region Access数据库连接
 public static DataSet Get(string sql)
 {
     OleDbConnection oleDb = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Application.StartupPath + @"\你的根目录下的库名;" + "Jet OLEDB:Database Password = 你的数据库密码");
     oleDb.Close();
     DataSet dataSet = new DataSet();
     DataTable datatable = new DataTable();
     oleDb.Open();
     OleDbDataAdapter dbDataAdapter = new OleDbDataAdapter(sql, oleDb);
     dbDataAdapter.Fill(datatable);
     dataSet.Tables.Add(datatable);
     oleDb.Close();
     return dataSet;
 }
 #endregion

3.导入方法

cs 复制代码
  public static DataTable ReadExcelFile(string filePath)
  {
      using (var package = new ExcelPackage(new FileInfo(filePath)))
      {
          ExcelWorksheet worksheet = package.Workbook.Worksheets[0];
          DataTable table = new DataTable();
          int columns = worksheet.Dimension.Columns;

          // 添加表格列
          for (int col = 1; col <= columns; col++)
          {
              table.Columns.Add(worksheet.Cells[1, col].Value.ToString());
          }

          // 添加数据行
          for (int row = 2; row <= worksheet.Dimension.Rows; row++)
          {
              DataRow dataRow = table.NewRow();
              for (int col = 1; col <= columns; col++)
              {
                  dataRow[col - 1] = worksheet.Cells[row, col].Value;
              }
              table.Rows.Add(dataRow);
          }
          return table;
      }
  }

4.使用导入方法到导入到数据库

cs 复制代码
  private void button3_Click(object sender, EventArgs e)
  {
      try
      {
          OpenFileDialog openFileDialog = new OpenFileDialog();
          openFileDialog.Filter = "Excel 文件 (*.xlsx)|*.xlsx|所有文件 (*.*)|*.*";
          openFileDialog.Title = "选择 Excel 文件";
          if (openFileDialog.ShowDialog() == DialogResult.OK)
          {
              string filePath = openFileDialog.FileName;
              // 构建 SQL 语句
              DataTable excelData = ReadExcelFile(filePath);
              foreach (DataRow row in excelData.Rows)
              {
                  //这里{row["姓名"]}是你单元格中对应的每一列的表头
                  Employee.Get($"INSERT INTO workers (Name,Age,Sex,Address,Salary,status) VALUES ('{row["姓名"]}',{row["年龄"]},'{row["性别"]}','{row["住址"]}','{row["薪资"].ToString().Replace("¥", "")}',0);");
              }
          }
          Flushed();//刷新数据
          NMessage("导入数据成功", NotificationType.Info);
      }
      catch (Exception ex)
      {
          NMessage("导入数据失败"+ex.Message, NotificationType.Error);
      }
  }
相关推荐
NineData4 小时前
数据库迁移总踩坑?用 NineData 迁移评估,提前识别所有兼容性风险
数据库·程序员·云计算
赵渝强老师6 小时前
【赵渝强老师】PostgreSQL中表的碎片
数据库·postgresql
Ray Liang8 小时前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
赵榕10 小时前
ClaimsPrincipal序列化为Json的正确姿势
.net
全栈老石11 小时前
拆解低代码引擎核心:元数据驱动的"万能表"架构
数据库·低代码
追逐时光者21 小时前
一款使用 C# 编写专为 Windows 11 打造的文件资源管理器增强工具!
后端·.net
倔强的石头_1 天前
kingbase备份与恢复实战(二)—— sys_dump库级逻辑备份与恢复(Windows详细步骤)
数据库
jiayou642 天前
KingbaseES 实战:深度解析数据库对象访问权限管理
数据库