打开EXCEL表格,批量写入到数据库
程序员文章站
2022-11-21 09:03:27
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms;using System.IO;using System.Data.OleDb;....
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Data.OleDb;
using System.Data.SqlClient;
namespace WindowsFormsApplication5
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
DataTable dt = new DataTable();
string connString = "Data Source=.;Initial Catalog=NIU123;Integrated Security=True";
SqlConnection conn;
//选择打开EXCEL表格
private void button1_Click(object sender, EventArgs e)
{
System.Windows.Forms.OpenFileDialog fd = new OpenFileDialog();
if (fd.ShowDialog() == DialogResult.OK)//调用这个方法打开选择对话框,并判断是否打开成功。
{
string fileName = fd.FileName;//把选种文件路径赋值给fileName.
bind(fileName);//调用这个方法
}
}
private void bind(string fileName)
{
//连接字符串
string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=\"Excel 12.0;HDR=YES\"";
//SQL语句
string strComm = "SELECT * FROM [Sheet1$]";
OleDbDataAdapter da = new OleDbDataAdapter(strComm, strConn);
DataSet ds = new DataSet();
try
{
da.Fill(ds,"SD");
dt = ds.Tables["SD"];
this.dataGridView1.DataSource = dt;
}
catch (Exception err)
{
MessageBox.Show("操作失败!" + err.ToString());
}
}
//写入到数据库
private void button2_Click(object sender, EventArgs e)
{
conn = new SqlConnection(connString);
conn.Open();
if (dataGridView1.Rows.Count > 0)
{
DataRow dr = null;
for (int i = 0; i < dt.Rows.Count; i++)
{
dr = dt.Rows[i];
insertToSql(dr);
}
conn.Close();
MessageBox.Show("导入成功!");
}
else
{
MessageBox.Show("没有数据!");
}
}
private void insertToSql(DataRow dr)
{
//excel表中的列名和数据库中的列名一定要对应
string name = dr["UserName"].ToString();
string password = dr["UserPassword"].ToString();
string sql = "insert into Table_20200625 values('" + name + "','" + password + "')";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
}
}
}
本文地址:https://blog.csdn.net/weixin_39195951/article/details/107302509
上一篇: MySQL定时备份数据库操作示例
推荐阅读
-
打开EXCEL表格,批量写入到数据库
-
php中使用ExcelFileParser处理excel获得数据(可作批量导入到数据库使用)
-
使用python批量读取word文档并整理关键信息到excel表格的实例
-
Java实现批量导入Excel表格数据到数据库中
-
【Javaweb】poi实现通过上传excel表格批量导入数据到数据库
-
excel 批量数据导入数据库与数据库导出数据到excel
-
使用python从excel批量导入数据到mysql数据库
-
php 把excel批量导入到数据库代码
-
php 把excel批量导入到数据库代码
-
thinkphp利用phpExcelReader导入Excel表格到数据库