我想通过asp.net读取Excel文件并存入到sql数据库中。现在已经通过fileupload控件和gridview控件实现了excel文件的上传和读取显示到gridview中,现在想通过一个button控件让读取到的数据存入到sql数据库的一个表中。
表是固定的,里面已经有数据了,读取的目标excel字段也是和数据库中表字段对应的,只是gridview的行读取有点糊涂了,一行一行的存,那这没一行中每一列有怎么定义,是不是用双循环?这又怎么循环呢?再者前面的gridview读到的数据在后面的button中就没有定义了,得重新读取~ 真糊涂了~~哪位老大给我点拨点拨啊,谢谢啦。
表是固定的,里面已经有数据了,读取的目标excel字段也是和数据库中表字段对应的,只是gridview的行读取有点糊涂了,一行一行的存,那这没一行中每一列有怎么定义,是不是用双循环?这又怎么循环呢?再者前面的gridview读到的数据在后面的button中就没有定义了,得重新读取~ 真糊涂了~~哪位老大给我点拨点拨啊,谢谢啦。
private DataTable XlsToDataTable(String strpath)
{
string strConn;
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + strpath + ";" +
"Extended Properties=Excel 8.0;";
OleDbConnection conn = new OleDbConnection(strConn);
OleDbDataAdapter myCommand = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", strConn);
DataTable dt = new DataTable();
myCommand.Fill(dt);
return dt;
} 绑定到gridview
using(SqlConnection conn=new SqlConnection(""))
{
SqlDataAdapter da=new SqlDataAdapter("",conn);da.Update(ds);
}
实现数据更新
myCommand.Fill(dt);
return dt;
} 绑定到gridview
using(SqlConnection conn=new SqlConnection(""))
{
SqlDataAdapter da=new SqlDataAdapter("",conn);da.Update(ds);
}
实现数据更新
{
SqlDataAdapter da=new SqlDataAdapter("",conn);da.Update(ds);
}
是不是用这个链接到数据库表单当点击上传时直接将数据更新到数据库中呢?
能给个代码示例不?
{
DataSet ds = (DataSet)Session["test"];
SqlConnection conm = Conn.getConnetion();
if (conm.State.ToString() == "Closed")
{
conm.Open();
}
SqlTransaction str2 = conm.BeginTransaction();
int k = 0;
if (ds.Tables[0].Rows.Count < 1)
{
Response.Write("<script>alert('没有数据!')</script>");
return;
}
try
{
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
string sqlStr2 = "insert into Finance(Fdate,Ftime,Fevikind,Fevino,Fjiefang,Fcredit,Fname,Fcountno,Flender,Fre,Fdetailno,Flag,Fcompare)values";
sqlStr2 += "('" + ds.Tables[0].Rows[i][0].ToString() + "',";
sqlStr2 += "'" + ds.Tables[0].Rows[i][1].ToString() + "',";
sqlStr2 += "'" + ds.Tables[0].Rows[i][2].ToString() + "',";
sqlStr2 += "'" + ds.Tables[0].Rows[i][3].ToString() + "',";
sqlStr2 += "'" + ds.Tables[0].Rows[i][4].ToString() + "',";
sqlStr2 += "'" + ds.Tables[0].Rows[i][5].ToString() + "',";
sqlStr2 += "'" + ds.Tables[0].Rows[i][6].ToString() + "',";
sqlStr2 += "'" + ds.Tables[0].Rows[i][7].ToString() + "',";
sqlStr2 += "'" + ds.Tables[0].Rows[i][8].ToString() + "',";
sqlStr2 += "'" + ds.Tables[0].Rows[i][9].ToString() + "',";
sqlStr2 += "'" + ds.Tables[0].Rows[i][10].ToString() + "',";
//sqlStr2 += "'" + ds.Tables[0].Rows[i][11].ToString() + "',";
//sqlStr2 += "'" + ds.Tables[0].Rows[i][11].ToString() + "')";
sqlStr2 += "'0')";
SqlCommand cmd2 = new SqlCommand(sqlStr2,conm,str2);
k += cmd2.ExecuteNonQuery();
}
str2.Commit();
}
catch (Exception ex)
{
Response.Write("发生异常,数据已回滚\n信息\n" + ex.Message);
str2.Rollback();
} finally
{
Response.Write("上传成功" + k + "条,转到数据比对模块进行数据比对!");
conm.Close();
}
upcomm.Connection.Open();
upcomm.ExecuteNonQuery();
upcomm.Connection.Close();
GridView1.Visible = false;
Button1.Visible = false;
fileId.Visible = false;
}
我最近得到的方法,亲身实践,可以用