将excel数据导入到数据库,用winfrom系统,如图:

该系统可以选择导入的excel文件,设置要导入的数据库的基本设置。
代码:
winfrom窗体:
public partial class exceldaosql : form
{
sqlconnn sqlcon = new sqlconnn();
public exceldaosql()
{
initializecomponent();
}
string str_excel_path;
private void exceldaosql_load(object sender, eventargs e)
{
txt_server.text = "(local)";
//cbox_server.text = "machine";
cbox_server.dropdownstyle = comboboxstyle.dropdownlist;
datatable dt = sqlcon.f1();
if (dt != null)
{
if (dt.rows.count != 0)
{
for (int i = 0; i < dt.rows.count; i++)
{
cbox_server.items.add(dt.rows[i][0].tostring().trim());//向控件中添加数据
}
}
}
ckbox_windows.checked = true;
txt_name.enabled = false;//禁用按钮
txt_pwd.enabled = false;
}
//选择多个excel文件
private void button1_click(object sender, eventargs e)
{
//只能打开一个文件------------------------------------------
openfiledialog1.filter = "excel文件|*.xlsx";//设置打开文件筛选器
openfiledialog1.title = "打开excel文件";//设置打开文件标题
openfiledialog1.multiselect = true;//允许选中多个文件
if (openfiledialog1.showdialog() == dialogresult.ok)//判断是否选择了文件
{
str_excel_path = openfiledialog1.filename.tostring();//获取选择的文件地址
txt_path.text = str_excel_path;//在textbox1中显示选择的文件地址
}
}
//获取sql server服务器上的所有数据库信息
private void button2_click(object sender, eventargs e)
{
cbox_server.items.clear();
datatable dt = sqlcon.f1();
if (dt != null)
{
if (dt.rows.count != 0)
{
for (int i = 0; i < dt.rows.count; i++)
{
cbox_server.items.add(dt.rows[i][0].tostring().trim());//向控件中添加数据
}
}
}
}
//将选择的excel表导入到sql server数据库中
private void button3_click(object sender, eventargs e)
{
if (txt_path.text != "")
{
string[] p_str_names = txt_path.text.split(',');//存储所有选择的excel文件名
string p_str_name = "";//储存遍历到的excel文件名
list<string> p_list_sheetnames = new list<string>();//创建泛型集合对象,用来存储工作表名称
for (int i = 0; i < p_str_names.length; i++)//遍历所有选择的excel文件名
{
p_str_name = p_str_names[i];//记录遍历到的excel文件名
p_list_sheetnames = getsheetname(p_str_name);//获取excel文件中的所有工作表名
for (int j = 0; j < p_list_sheetnames.count; j++)//遍历所有工作表
{
if (ckbox_windows.checked)//用windows身份验证登录sql server
//将工作表内容导出到sql server
{
importdatatosql(p_str_name, p_list_sheetnames[j], "data source='" + txt_server.text + "';initial catalog='" + cbox_server.text + "';integrated security=true;");
}
else if (ckbox_sql.checked)//用sql server身份验证登录sql server
{
importdatatosql(p_str_name, p_list_sheetnames[j], "data source='" + txt_server.text + "'database='" + cbox_server.text + "';uid='" + txt_name.text + "';pwd='" + txt_pwd.text + "';");
}
}
}
messagebox.show("已经将所有选择的excel工作表导入到了sql server数据库中!", "提示", messageboxbuttons.ok, messageboxicon.information);
}
else
{
messagebox.show("请选择需要导入数据库的文件!");
}
}
//获取excel文件中的所有工作表名称
private list<string> getsheetname(string p_str_name)
{
list<string > p_list_sheetname=new list<string> ();//创建泛型集合对象
//连接excel数据库
//oledbconnection olecon = new oledbconnection("provider=microsoft.jet.oledb.4.0;data source=" + p_str_name + ";extended properties=excel 8.0;");
oledbconnection olecon = new oledbconnection("provider=microsoft.ace.oledb.12.0;data source=" + p_str_name + ";extended properties=\"excel 12.0;hdr=yes;imex=1;\"");
olecon.open();//打开数据库连接
system.data.datatable dtable = olecon.getschema("tables");//创建表对象
datatablereader dtreader = new datatablereader(dtable);//创建表读取对象
while (dtreader.read())
{
string p_str_sname=dtreader ["table_name"].tostring ().replace ('$',' ').trim ();//记录工作表名称
if (!p_list_sheetname.contains(p_str_sname))//判断泛型集合是否已经存在该工作表名称
p_list_sheetname.add(p_str_sname);//将工作表加入到泛集合中
}
dtable =null;//清空表对象
dtreader =null ;//清空表读取对象
olecon .close ();//关闭数据库连接
return p_list_sheetname ;
}
/*将excel中指定工作表内容导入sql server数据库中*/
public void importdatatosql(string p_str_excel,string p_str_sheetname,string p_str_sqlcon)
{
dataset myds = new dataset();//创建数据集对象
try
{
//获得全部数据
//string p_str_oledbcon = "provider=microsoft.jet.oledb.4.0;data source=" + p_str_excel + ";extended properties=excel 8.0;";
string p_str_oledbcon = "provider=microsoft.ace.oledb.12.0;data source=" + p_str_excel + ";extended properties=\"excel 12.0;hdr=yes;imex=1;\"";
oledbconnection oledbcon = new oledbconnection(p_str_oledbcon);//创建oledb数据库连接对象
string p_str_excelsql = "";//记录要执行的excel查询语句
oledbdataadapter oledbda = null;//创建oledb数据桥接器对象
p_str_excelsql = string.format("select * from [{0}$]",p_str_sheetname);//记录要执行的excel查询语句
oledbda = new oledbdataadapter(p_str_excelsql, p_str_oledbcon);//使用数据桥接器执行excel查询
oledbda.fill(myds, p_str_sheetname);//填充数据
//定义变量,用来记录创建表的sql语句
string p_str_createsql = string.format("create table {0}(", p_str_sheetname);
foreach (datacolumn c in myds .tables [0].columns )//遍历数据集中的所有行
{
p_str_createsql += string.format("[{0}]text,", c.columnname);//在表中创建字段
}
p_str_createsql = p_str_createsql + ")";//完善创建表的sql语句
//创建sql数据库连接对象
using (sqlconnection sqlcon=new sqlconnection (p_str_sqlcon ))
{
sqlcon.open();//打开数据库连接
sqlcommand sqlcmd = sqlcon.createcommand();//创建执行命令对象
sqlcmd.commandtext = p_str_createsql;//指定要执行的sql数据
sqlcmd.executenonquery();//执行操作
sqlcon.close();//关闭数据库连接
}
using (sqlbulkcopy bcp = new sqlbulkcopy(p_str_sqlcon))//用bcp导入数据
{
bcp.batchsize = 100;//每次传输的行数
bcp.destinationtablename = p_str_sheetname;//定义目标表
bcp.writetoserver(myds.tables[0]);//将数据写入sql server数据表
}
}
catch
{
messagebox.show("sql server 数据库中已经存在" + p_str_sheetname + "表!", "警告", messageboxbuttons.ok, messageboxicon.warning);
}
}
private void ckbox_windows_checkedchanged(object sender, eventargs e)
{
if (ckbox_windows.checkstate == checkstate.checked)//当选择windows身份验证
{
ckbox_sql.checked = false ;//sql server身份验证不能选中
//txt_name.readonly = true;//设为只读
//txt_pwd.readonly = true;
txt_name.enabled = false;//禁用按钮
txt_pwd.enabled = false;
txt_name.text = "";
txt_path.text = "";
txt_path.text = str_excel_path;//在textbox1中显示选择的文件地址
}
else
{
ckbox_sql.checked = true ;
//txt_name.readonly = false ;//设为只读
//txt_pwd.readonly = false;
txt_name.enabled = true;//启用按钮
txt_pwd.enabled = true;
txt_name.text = "sa";
txt_path.text = "";
txt_path.text = str_excel_path;//在textbox1中显示选择的文件地址
}
}
private void ckbox_sql_checkedchanged(object sender, eventargs e)
{
if (ckbox_sql.checkstate == checkstate.checked)
{
ckbox_windows.checked = false;
//txt_name.readonly = false;//设为只读
//txt_pwd.readonly = false;
txt_name.enabled = true ;//启用按钮
txt_pwd.enabled = true;
txt_name.text = "sa";
txt_path.text = "";
txt_path.text = str_excel_path;//在textbox1中显示选择的文件地址
}
else
{
ckbox_windows.checked = true ;
//txt_name.readonly = true;//设为只读
//txt_pwd.readonly = true;
txt_name.enabled = false;//禁用按钮
txt_pwd.enabled = false;
txt_name.text = "";
txt_path.text = "";
txt_path.text = str_excel_path;//在textbox1中显示选择的文件地址
}
}
}
连接数据库的类:sqlconnn
class sqlconnn
{
private static string constr = "server=(local);initial catalog=d_total;integrated security=true";
// private static string constr = "data source =192.168.1.201;initial catalog=d_total23 ;user id=sa;password=123";
public datatable f1()
{
string a = "select name from master..sysdatabases";//查询本数据库信息
return only_table1(a);
}
public datatable only_table1(string exec)
{
system.data.datatable dt_jdl = new datatable();
try
{
using (sqlconnection con = new sqlconnection(constr))
{
if (con.state == connectionstate.closed)
{
con.open();
} if (con.state == connectionstate.open || con.state == connectionstate.connecting)
{
sqldataadapter sda2 = new sqldataadapter(exec, con);//全部通過寫存儲過程即可
dataset ds2 = new dataset();
sda2.fill(ds2, "cxq");
dt_jdl = ds2.tables["cxq"];
sda2.dispose();
ds2.dispose();
}
con.close();
}
return dt_jdl;
}
catch (exception ex)
{
return null;
}
}
}
系统优点:可以导入excel的多个工作表的数据
系统有一个缺陷:无法将相同的表导入数据库多次,也就是说只能导入数据库一次,无法覆盖和添加。
到此这篇关于c#实现excel数据导入到sql server数据库的文章就介绍到这了,更多相关c# excel数据导入到数据库内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论