当前位置: 编程技术>.net/c#/asp.net
asp.net 将xls文件导入数据库中的代码
来源: 互联网 发布时间:2014-08-30
本文导语: 完整代码(xls导入数据库): 代码示例: protected void Click() { string postName=file1.PostedFile.FileName; if (postName == "") { Response.Write("alert('请先选择文件.');location='add.aspx';"); } else { string str = this.UpLoadFile(); if (str == "Erro...
完整代码(xls导入数据库):
代码示例:
protected void Click()
{
string postName=file1.PostedFile.FileName;
if (postName == "")
{
Response.Write("alert('请先选择文件.');location='add.aspx';");
}
else
{
string str = this.UpLoadFile();
if (str == "Error")
{
Response.Write("alert('上传xls文件失败.');location='add.aspx';");
}
else
{
string mystring = "Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = "+str+";Extended Properties=Excel 8.0";
OleDbConnection cnnxls = new OleDbConnection(mystring);
OleDbDataAdapter myDa = new OleDbDataAdapter("select * from [Sheet1$]", cnnxls);
DataSet myDs = new DataSet();
myDa.Fill(myDs);
if (myDs.Tables[0].Rows.Count > 0)
{
string strSql = "";
string CnnString = "Provider=SQLOLEDB;database=testnews;server=(local);uid=sa;pwd=";
OleDbConnection conn = new OleDbConnection(CnnString);
conn.Open();
OleDbCommand myCmd = null;
for (int i = 0; i < myDs.Tables[0].Rows.Count; i++)
{
strSql = "insert into website(sname,surl) values ('";
strSql += myDs.Tables[0].Rows[i].ItemArray[0].ToString() + "', '";
strSql += myDs.Tables[0].Rows[i].ItemArray[1].ToString() + "')";
try
{
myCmd = new OleDbCommand(strSql, conn);
myCmd.ExecuteNonQuery();
Response.Write("alert('数据导入成功.');location='index.aspx';");
}
catch
{
Response.Write("alert('数据导入失败.');location='add.aspx';");
}
}
}
}
}
{
string postName=file1.PostedFile.FileName;
if (postName == "")
{
Response.Write("alert('请先选择文件.');location='add.aspx';");
}
else
{
string str = this.UpLoadFile();
if (str == "Error")
{
Response.Write("alert('上传xls文件失败.');location='add.aspx';");
}
else
{
string mystring = "Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = "+str+";Extended Properties=Excel 8.0";
OleDbConnection cnnxls = new OleDbConnection(mystring);
OleDbDataAdapter myDa = new OleDbDataAdapter("select * from [Sheet1$]", cnnxls);
DataSet myDs = new DataSet();
myDa.Fill(myDs);
if (myDs.Tables[0].Rows.Count > 0)
{
string strSql = "";
string CnnString = "Provider=SQLOLEDB;database=testnews;server=(local);uid=sa;pwd=";
OleDbConnection conn = new OleDbConnection(CnnString);
conn.Open();
OleDbCommand myCmd = null;
for (int i = 0; i < myDs.Tables[0].Rows.Count; i++)
{
strSql = "insert into website(sname,surl) values ('";
strSql += myDs.Tables[0].Rows[i].ItemArray[0].ToString() + "', '";
strSql += myDs.Tables[0].Rows[i].ItemArray[1].ToString() + "')";
try
{
myCmd = new OleDbCommand(strSql, conn);
myCmd.ExecuteNonQuery();
Response.Write("alert('数据导入成功.');location='index.aspx';");
}
catch
{
Response.Write("alert('数据导入失败.');location='add.aspx';");
}
}
}
}
}