ASP.NET中如何讲Excel表格中的数据导入到SQLServer中去?

数据库是2000的。 希望大侠们能给出具体的代码。 谢谢
2024-11-17 14:17:14
推荐回答(1个)
回答(1):

不管你是那个数据库,将Excel里面的数据导入到数据库中的原理就是将Excel里面的数据存储到一个dataTable中,然后将数据一行一行添加到数据库的表里。
SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["aa"].ToString());
con.Open();//数据库连接字符串

DataTable dtXls = new DataTable();
if (this.fudAdd.PostedFile.FileName.ToString().Trim() != "" && this.fudAdd.PostedFile.FileName!=null)
{
string filePath = this.fudAdd.PostedFile.FileName.ToString().Trim();
FileInfo fileTag = new FileInfo(fudAdd.PostedFile.FileName);
string extendedName = fileTag.Extension;
if (extendedName.ToLower() != ".xls" && extendedName.ToLower() != ".xlsx")
{
Response.Write("");
return;
}
else
{
dtXls = ExcelToDataTable(filePath,extendedName);
if (dtXls==null||dtXls.Rows.Count <= 0 || dtXls.Columns[0].ToString() == "")
{
Response.Write("");
return;
}
else
{
if (dtXls.Columns[0].ToString() != "手机号码" || dtXls.Columns[1].ToString() != "状态")
{
Response.Write("");
return;
}
else
{
if (dtXls.Rows[0][0].ToString() == "")
{
Response.Write("");
return;
}
else
{
string result = AddXlsData(dtXls, con);
string[] resultData = result.Split('-');
string msg = "资料上传成功!共计" + resultData[0] + "条成功," + resultData[1] + "条失败!";
Response.Write("");
logwrite.LogOpera(userid, "UnExistMobile_Mag.aspx", "UnExistMobile_Mag.aspx.cs", "成功上传一批空号");//记录log
BindData();
return;
}
}
}
}
con.Close();

//
#region ExcelToDataTable
///


/// 读取xls文件
/// Add by
///

///
///
protected DataTable ExcelToDataTable(string fileName, string extendedName)
{
string strConn = string.Empty;
if (extendedName.ToLower() == ".xls")
{
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1';";
}
if (extendedName.ToLower() == ".xlsx")
{
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties='Excel 12.0;HDR=YES'";
}

OleDbConnection conn = new OleDbConnection(strConn);
conn.Open();
System.Data.DataTable schemaTable = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null);
string tableName = schemaTable.Rows[0][2].ToString().Trim();

string strExcel = "";
OleDbDataAdapter myCommand = null;
DataSet ds = null;
strExcel = "Select * From [" + tableName + "]";
myCommand = new OleDbDataAdapter(strExcel, strConn);

ds = new DataSet();

myCommand.Fill(ds, tableName);
if (ds != null)
{
System.Data.DataTable dt = ds.Tables[0];
return dt;
}
else
{
return null;
}
conn.Close();
ds.Dispose();
}
#endregion