这里我使用了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);
}
}