C# 如何将EXCEL插入到数据库? 20
C#到底如何将EXCEL插入到数据库?我按照如下程序写,数据库始终没有导入EXCEL表中的数据://***********************************...
C# 到底如何将EXCEL插入到数据库?我按照如下程序写,数据库始终没有导入EXCEL表中的数据:
//************************************************************|
// Import_Excel() |
//************************************************************|
private void Import_Excel()
{
//加载excel文件
string fileName = Open_File();//打开对话框,获得文件名
string excelStr = "Provider= Microsoft.Ace.OleDB.12.0;Data Source=" + fileName + ";Extended
Properties='Excel 12.0;HDR=YES;IMEX=1'";//execl 2007
// 将EXCEL中的表存入dataset
DataSet ds = new DataSet();
using (System.Data.OleDb.OleDbConnection cn = new OleDbConnection(excelStr))
{
using (OleDbDataAdapter dr = new OleDbDataAdapter("SELECT * FROM [sheet$]", excelStr))
{
dr.Fill(ds);
}
}
//数据库设置
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=countyset.accdb";
string selectQuery = "select * from Sheet";
OleDbCommand cmd = new OleDbCommand(selectQuery, conn);
OleDbDataAdapter myAdapter = new OleDbDataAdapter();
myAdapter.SelectCommand = cmd;
OleDbCommandBuilder cmdBuilder = new OleDbCommandBuilder(myAdapter);
myAdapter.Update (ds); //将ds的数据更新到数据库
} 展开
//************************************************************|
// Import_Excel() |
//************************************************************|
private void Import_Excel()
{
//加载excel文件
string fileName = Open_File();//打开对话框,获得文件名
string excelStr = "Provider= Microsoft.Ace.OleDB.12.0;Data Source=" + fileName + ";Extended
Properties='Excel 12.0;HDR=YES;IMEX=1'";//execl 2007
// 将EXCEL中的表存入dataset
DataSet ds = new DataSet();
using (System.Data.OleDb.OleDbConnection cn = new OleDbConnection(excelStr))
{
using (OleDbDataAdapter dr = new OleDbDataAdapter("SELECT * FROM [sheet$]", excelStr))
{
dr.Fill(ds);
}
}
//数据库设置
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=countyset.accdb";
string selectQuery = "select * from Sheet";
OleDbCommand cmd = new OleDbCommand(selectQuery, conn);
OleDbDataAdapter myAdapter = new OleDbDataAdapter();
myAdapter.SelectCommand = cmd;
OleDbCommandBuilder cmdBuilder = new OleDbCommandBuilder(myAdapter);
myAdapter.Update (ds); //将ds的数据更新到数据库
} 展开
展开全部
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Collections;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Data.Common;
using System.Data.SqlClient;
public partial class Excel导入_Default : System.Web.UI.Page
{
private static string filename;
private static string savePath;
private static DataSet ds; //要插入的数据
private static DataTable dt;
protected void Page_Load(object sender, EventArgs e)
{
}
//上传文件到指定的服务器
protected void Button1_Click1(object sender, EventArgs e)
{
filename = this.fileUploadExcel.FileName;
//savePath必须包含表名在内的所有路径名
savePath = @"G:\项目组文件\项目.net学习资料\工程\Health\Excel导入\Files\" + this.fileUploadExcel.FileName; //上传服务器文件的存储,存在当前新建的文件夹
this.fileUploadExcel.SaveAs(savePath);
Boolean judge_excel = Judge_Excel();
if (!judge_excel)
{
MessageBox.Show("上传的不是excel文件", "标题", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
return;
}
else
MessageBox.Show("上传文件成功", "标题", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
//测试,将excel中的sheet1导入到sqlserver中
//string connString = "server=localhost;uid=sa;pwd=sqlgis;database=master";
//System.Windows.Forms.OpenFileDialog fd = new OpenFileDialog();
//if (fd.ShowDialog() == DialogResult.OK)
//{
// //TransferData(fd.FileName, "sheet1", connString);
//}
}
//判断文件是否是excel文件函数
protected Boolean Judge_Excel()
{
string fileExtend = System.IO.Path.GetExtension(this.fileUploadExcel.FileName);
if (fileExtend == ".xlsx" || fileExtend == ".xls")
return true;
else
return false;
}
//获取excel数据按钮的触发,
protected void Button2_Click(object sender, EventArgs e)
{
ExcelToDataSet();
MessageBox.Show("获取数据成功", "标题", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
}
//从excel表中获取数据的函数
public void ExcelToDataSet()
{
string strConn = "Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = " + savePath + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\"";
OleDbConnection conn = new OleDbConnection(strConn); //连接excel
if (conn.State.ToString() == "Open")
{
conn.Close();
}
conn.Open(); //外部表不是预期格式,不兼容2010的excel表结构
string s = conn.State.ToString();
OleDbDataAdapter myCommand = null;
ds = null;
/*DataTable yTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new Object[] { null, null, null, "TABLE" });//获取表的框架,几行几列
string tableName = yTable.Rows[0]["filename"].ToString(); //表示的是几行几列
string strSel = "select * from [" + filename + "]";//xls */
string strExcel = "select * from [sheet1$]"; //如果有多个sheet表时可以选择是第几张sheet表
myCommand = new OleDbDataAdapter(strExcel, conn);//用strExcel初始化myCommand,查看myCommand里面的表的数据??
ds = new DataSet();
myCommand.Fill(ds); //把表中的数据存放在ds(dataSet)
conn.Close();
try
{
dt = ds.Tables[0];
this.dataGridView1.DataSource = dt;
}
catch (Exception err)
{
MessageBox.Show("操作失败!" + err.ToString());
}
}
//excel导入数据库sql的按钮触发
protected void Button3_Click(object sender, EventArgs e)
{
//string path = @"D:\数据库SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\Test.mdf";
string connString = "server=localhost;uid=sa;pwd=1234;database=Test"; //连接数据库的路径方法
//String connString=@"server=localhost;uid=sa;pwd=1234;database=D:\数据库SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\Test.mdf";
SqlConnection conn = new SqlConnection(connString);
conn.Open();
DataRow dr = null;
int C_Count = dt.Columns.Count;//获取列数
for (int i = 0; i < dt.Rows.Count; i++) //记录表中的行数,循环插入
{
dr = dt.Rows[i];
insertToSql(dr, C_Count, conn);
}
conn.Close();
if (dataGridView1.Rows.Count > 0) //把数据库表中的数据显示到表中,可判断有没有数据
{
MessageBox.Show("导入成功!");
}
else
{
MessageBox.Show("没有数据!");
}
}
//使用bcp,不容易出错而且效率高
/*try
{
using (System.Data.SqlClient.SqlBulkCopy bcp = new System.Data.SqlClient.SqlBulkCopy(connString))
{
bcp.SqlRowsCopied += new System.Data.SqlClient.SqlRowsCopiedEventHandler(bcp_SqlRowsCopied);
bcp.BatchSize = 100;//每次传输的行数
bcp.NotifyAfter = 100;//进度提示的行数
bcp.DestinationTableName = savePath;//目标表
bcp.WriteToServer(ds.Tables[0]);
}
}
catch
{
System.Windows.Forms.MessageBox.Show(ex.Message);
}*/
//插入数据库的函数
protected void insertToSql(DataRow dr, int column_count, SqlConnection conn)
{
//excel表中的列名和数据库中的列名一定要对应
string name = dr[0].ToString();//需要把内个列都列出来
string age = dr[1].ToString();
string sex = dr[2].ToString();
//当数据库中有多个表时,怎么分辨插入的表
string sql = "insert into 客户 values('" + name + "','" + age + "','" + sex + "')";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
}
//从excel表中获取数据并存在
// protected void ImportFromExcel()
// {
// string execelConnectionStr = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=filename;
// Extended Properties=""Excel 8.0;HDR=YES;IMEX=1\""";//表第一行是标题,不做为数据使用, Excel 档案只能用来做“读取”用途。
// ds = new DataSet();
// string connString = "Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = "
// + savePath + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\"";
// DataTable table = OleDbHelper.GetExcelTables(connString);
// if (table == null || table.Rows.Count <= 0)
// {
// return;
// }
// foreach (DataRow dr in table.Rows)
// {
// string cmdText = "select * from [" + dr["TABLE_NAME"].ToString() + "]";
// DataTable dt = OleDbHelper.FillDataTable(connString, cmdText);
// dt.TableName = dr["TABLE_NAME"].ToString();
// ds.Tables.Add(dt);
// }
// }
}
展开全部
先在类中定义一个方法名为ExecleDs的方法,用于将Excel表里的数据填充到DataSet中,代码如下
public DataSet ExecleDs(stringfilenameurl,string table)
2 {
3 string strConn = "Provider=Microsoft.Jet.OleDb.4.0;" + "datasource=" +filenameurl+ ";Extended Properties='Excel 8.0; HDR=YES;IMEX=1'";
4 OleDbConnection conn = new OleDbConnection(strConn);
5
6 OleDbDataAdapter odda = new OleDbDataAdapter("select* from [Sheet1$]",conn);
7 DataSet ds = newDataSet();
8 odda.Fill(ds,table);
9
10 return ds;
11
12 }
然后设计页面,在此作个简单的页面
<table style="width:395px; height: 84px" border="1">
2 <tr>
3 <tdstyle="width:380px" align="center">
4 批量导入用户信息</td>
5 </tr>
6 <tr>
7 <tdstyle="width: 100px">
8 <asp:FileUploadID="FileUpload1" runat="server" Width="380px" /></td>
9 </tr>
10 <tr>
11 <tdstyle="width:380px" align="center">
12 <asp:ButtonID="Button1" runat="server" Text="添加" OnClick="Button1_Click" /></td>
13 </tr>
14 </table>
15 <asp:Label ID="Label1" runat="server" Width="466px"></asp:Label>
当点击添加按钮时激发事件,代码如下
protectedvoid Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile == false)
{
Response.Write("<script>alert('请您选择Excel文件')</script>");
return;//当无文件时,返回
}
stringIsXls=System.IO.Path.GetExtension(FileUpload1.FileName).ToString().ToLower();
if (IsXls != ".xls")
{
Response.Write("<script>alert('只可以选择Excel文件')</script>");
return;//当选择的不是Excel文件时,返回
}
string error = null;
Access.Class1 ac = newAccess.Class1();
SqlConnection cn = ac.myConnection();
cn.Open();
string strpath =FileUpload1.PostedFile.FileName.ToString(); //获取Execle文件路径
stringfilename =FileUpload1.FileName; //获取Execle文件名
DataSet ds = ac.ExecleDs(strpath,filename);
DataRow[] dr = ds.Tables[0].Select(); //定义一个DataRow数组
introwsnum = ds.Tables[0].Rows.Count;
if (rowsnum == 0)
{
Response.Write("<script>alert('Excel表为空表,无数据!')</script>"); //当Excel表为空时,对用户进行提示
}
else
{
for (int i= 0; i < dr.Length; i++)
{
stringYHMC = dr[i]["YongHuMingCheng"].ToString();
stringYHMM = dr[i]["YongHuMiMa"].ToString();
stringDQRQ = dr[i]["DaoQiRiQi"].ToString();
stringZT = dr[i]["ZhuangTai"].ToString();
stringTJSJ = dr[i]["TianJiaShiJian"].ToString();
stringJXDM = dr[i]["JiaXiaoDaiMa"].ToString();
stringsqlcheck = "select count(*)from DC_YongHuLieBiao where YongHuMingCheng='" + YHMC + "'AndJiaXiaoDaiMa='" + JXDM + "'"; //检查用户是否存在
boolch = ac.check(sqlcheck);
if(ch == true)
{
stringinsertstr = "insert intoDC_YongHuLieBiao(YongHuMingCheng,YongHuMiMa,DaoQiRiQi,ZhuangTai,TianJiaShiJian,JiaXiaoDaiMa)values('" +
YHMC + "','" + YHMM + "','"+ DQRQ + "','" + ZT + "','"+ TJSJ + "','" + JXDM + "')";
SqlCommand cmd = new SqlCommand(insertstr,cn);
try
{
cmd.ExecuteNonQuery();
} catch (MembershipCreateUserExceptionex) //捕捉异常
{
Response.Write("<script>alert('创建用户:"+ex.Message+"')</script>");
}
}
else
{
error += "<emstyle='color:red;font-sixe:25px'>"+YHMC+"</em>用户已存在,此行记录无法插入!请修改用户再进行插入 <br>"; //若用户存在,将已存在用户信息打出,并提示此用户无法插入
continue;
}
}
Response.Write("<script>alert('Excle表导入成功!')</script>");
Label1.Text= error;
}
cn.Close();
}
public DataSet ExecleDs(stringfilenameurl,string table)
2 {
3 string strConn = "Provider=Microsoft.Jet.OleDb.4.0;" + "datasource=" +filenameurl+ ";Extended Properties='Excel 8.0; HDR=YES;IMEX=1'";
4 OleDbConnection conn = new OleDbConnection(strConn);
5
6 OleDbDataAdapter odda = new OleDbDataAdapter("select* from [Sheet1$]",conn);
7 DataSet ds = newDataSet();
8 odda.Fill(ds,table);
9
10 return ds;
11
12 }
然后设计页面,在此作个简单的页面
<table style="width:395px; height: 84px" border="1">
2 <tr>
3 <tdstyle="width:380px" align="center">
4 批量导入用户信息</td>
5 </tr>
6 <tr>
7 <tdstyle="width: 100px">
8 <asp:FileUploadID="FileUpload1" runat="server" Width="380px" /></td>
9 </tr>
10 <tr>
11 <tdstyle="width:380px" align="center">
12 <asp:ButtonID="Button1" runat="server" Text="添加" OnClick="Button1_Click" /></td>
13 </tr>
14 </table>
15 <asp:Label ID="Label1" runat="server" Width="466px"></asp:Label>
当点击添加按钮时激发事件,代码如下
protectedvoid Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile == false)
{
Response.Write("<script>alert('请您选择Excel文件')</script>");
return;//当无文件时,返回
}
stringIsXls=System.IO.Path.GetExtension(FileUpload1.FileName).ToString().ToLower();
if (IsXls != ".xls")
{
Response.Write("<script>alert('只可以选择Excel文件')</script>");
return;//当选择的不是Excel文件时,返回
}
string error = null;
Access.Class1 ac = newAccess.Class1();
SqlConnection cn = ac.myConnection();
cn.Open();
string strpath =FileUpload1.PostedFile.FileName.ToString(); //获取Execle文件路径
stringfilename =FileUpload1.FileName; //获取Execle文件名
DataSet ds = ac.ExecleDs(strpath,filename);
DataRow[] dr = ds.Tables[0].Select(); //定义一个DataRow数组
introwsnum = ds.Tables[0].Rows.Count;
if (rowsnum == 0)
{
Response.Write("<script>alert('Excel表为空表,无数据!')</script>"); //当Excel表为空时,对用户进行提示
}
else
{
for (int i= 0; i < dr.Length; i++)
{
stringYHMC = dr[i]["YongHuMingCheng"].ToString();
stringYHMM = dr[i]["YongHuMiMa"].ToString();
stringDQRQ = dr[i]["DaoQiRiQi"].ToString();
stringZT = dr[i]["ZhuangTai"].ToString();
stringTJSJ = dr[i]["TianJiaShiJian"].ToString();
stringJXDM = dr[i]["JiaXiaoDaiMa"].ToString();
stringsqlcheck = "select count(*)from DC_YongHuLieBiao where YongHuMingCheng='" + YHMC + "'AndJiaXiaoDaiMa='" + JXDM + "'"; //检查用户是否存在
boolch = ac.check(sqlcheck);
if(ch == true)
{
stringinsertstr = "insert intoDC_YongHuLieBiao(YongHuMingCheng,YongHuMiMa,DaoQiRiQi,ZhuangTai,TianJiaShiJian,JiaXiaoDaiMa)values('" +
YHMC + "','" + YHMM + "','"+ DQRQ + "','" + ZT + "','"+ TJSJ + "','" + JXDM + "')";
SqlCommand cmd = new SqlCommand(insertstr,cn);
try
{
cmd.ExecuteNonQuery();
} catch (MembershipCreateUserExceptionex) //捕捉异常
{
Response.Write("<script>alert('创建用户:"+ex.Message+"')</script>");
}
}
else
{
error += "<emstyle='color:red;font-sixe:25px'>"+YHMC+"</em>用户已存在,此行记录无法插入!请修改用户再进行插入 <br>"; //若用户存在,将已存在用户信息打出,并提示此用户无法插入
continue;
}
}
Response.Write("<script>alert('Excle表导入成功!')</script>");
Label1.Text= error;
}
cn.Close();
}
本回答被网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
你的问题在于sqlcommandbuilder的使用,首先用这个必须在selectcommand中包含唯一值的列,所以,要么你的数据库做个主键,其次要先用selectcommand从数据库读数据到ds,哪怕是空数据。然后再把excel数据导入ds,最后update(ds)
追问
能不能具体点呢?
追答
其实你去看看sqlcommandbuiler的说明就大概能明白,我简单写点代码,你自己补全吧
void Inport_excel()
{
datatable dt=new datatable();
\\先用dataadapter填充dt
sqlcommand cmd=new sqlcommand(“select * from table”,sqlconnection);
sqldataadapter sda=new sqldataadapter();
sda.selectcommand=cmd;
sqlcommandbuilder builder=new sqlcommandbuilder(sda);
cmd.fill(dt);
\\哪怕你的数据库的table里没有数据,也要先填充dt
\\这时builder会自动生成cmd的updatecommand
\\现在才往dt里导excel的数据
---代码----
最后执行
cmd.update(dt);
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询