ASP.NET导入Excel到SQL数据库

时间:2023-03-08 17:52:28

protected void btnChange_Click(object sender, EventArgs e)

{

UserInfoClass tClass = (UserInfoClass)Session["UserInfo"];

string tLanguageType = tClass.Language;

//获取文件路径

string filePath = this.file1.PostedFile.FileName;

if (filePath != "")

{

if (filePath.Contains("xls"))//判断文件是否存在

{

InputExcel(filePath);

}

else

{

MessageBox.Show("请检查您选择的文件是否为Excel文件!谢谢!");

}

}

else

{

MessageBox.Show("请先选择导入文件后,再执行导入!谢谢!");

}

}

private void InputExcel(string pPath)

{

string conn = "Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source =" + pPath + ";Extended Properties='Excel 8.0;HDR=False;IMEX=1'";

OleDbConnection oleCon = new OleDbConnection(conn);

oleCon.Open();

string Sql = "select * from [Sheet1$]";

OleDbDataAdapter mycommand = new OleDbDataAdapter(Sql, oleCon);

DataSet ds = new DataSet();

mycommand.Fill(ds, "[Sheet1$]");

oleCon.Close();

int count = ds.Tables["[Sheet1$]"].Rows.Count;

for (int i = 0; i < count; i++)

{

string tUserID, tUserName, tDept, tEmail, tLeader, tAngent;

tUserID = ds.Tables["[Sheet1$]"].Rows[i]["員工代號"].ToString().Trim();

tUserName = ds.Tables["[Sheet1$]"].Rows[i]["員工姓名"].ToString().Trim();

tDept = ds.Tables["[Sheet1$]"].Rows[i]["所屬部門代號"].ToString().Trim();

tEmail= ds.Tables["[Sheet1$]"].Rows[i]["E-Mail Address"].ToString().Trim();

tLeader = ds.Tables["[Sheet1$]"].Rows[i]["直属主管"].ToString().Trim();

tAngent = ds.Tables["[Sheet1$]"].Rows[i]["代理人"].ToString().Trim();

string excelsql = "insert into " + this.UserInfo.Company + "..[resak] (resak001, resak002, resak015,resak005,resak013,resak009) values ('" + tUserID + "','" + tUserName + "','" + tDept + "','" + tEmail + "','" + tLeader + "','" + tAngent + "')";

DBCommand cmd = DscDBData.GetDataDBCommand();

cmd.ExeNonQuery(excelsql);

}

}

当然此部分内容拿过来要稍作修改,比如最后的执行Insert语句的部分,等内容。

上面完成了ASP.NET下导入Excel到数据库的功能。