国内优秀的企业网站,有关于网站建设类似的文章,汽修网站怎么做,千图网免费素材图库海报这里我使用了Access数据库为例#xff0c;导入EPPlus如果不会请看上一篇帖子
1.首先先设置EPPlus为非商业使用 public Homes(){InitializeComponent();ExcelPackage.LicenseContext OfficeOpenXml.LicenseContext.NonCommercial; // 设置EPPlus为非商业使用}
2.Access数据…这里我使用了Access数据库为例导入EPPlus如果不会请看上一篇帖子
1.首先先设置EPPlus为非商业使用 public Homes(){InitializeComponent();ExcelPackage.LicenseContext OfficeOpenXml.LicenseContext.NonCommercial; // 设置EPPlus为非商业使用}
2.Access数据库连接方法 #region Access数据库连接public static DataSet Get(string sql){OleDbConnection oleDb new OleDbConnection(ProviderMicrosoft.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.导入方法 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.使用导入方法到导入到数据库 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);}}