Excel数据导入SQL数据库中的对应表——C#WEB开发问题。
当感情变旧 2015-04-26 12:51:35 下面是获取Excel数据的代码:
HttpPostedFile p = fUExcel.PostedFile;
string filename = DateTime.Now.ToString("yyyyMMddHHmm") + Path.GetFileName(p.FileName);
if (!Directory.Exists(Server.MapPath(@"~/upload" + "//")))
Directory.CreateDirectory(Server.MapPath(@"~/upload" + "//"));
string filePath = Server.MapPath(@"~/upload" + "//" + filename);
fUExcel.SaveAs(filePath);
if (filename != "")
{
if (filename.Contains("xls"))
{
System.Data.DataTable dt = null;
OleDbConnection oleCon = new OleDbConnection("Provider=Microsoft.Jet.Oledb.4.0;Data Source='" + filePath + "';Extended Properties='Excel 8.0;HDR=Yes;IMEX=2;'");
oleCon.Open();
System.Data.DataTable schemaTable = oleCon.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string sheetName = schemaTable.Rows[0]["TABLE_NAME"].ToString().Trim();
string Sql = "select * from [" + sheetName + "]";
OleDbDataAdapter mycommand = new OleDbDataAdapter(Sql, oleCon);
DataSet ds = new DataSet();
mycommand.Fill(ds, "[+ sheetName +]");
oleCon.Close();
dt = ds.Tables[0];
接下来应该是将数据再录入数据库,代码是这样的
:
foreach (DataRow dr in dt.Rows)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Students"].ConnectionString);
try
{
int i = 0;
string lng = dr["LNG"].ToString().Trim();
string lat = dr["LAT"].ToString().Trim();
string offsetLNG = dr["OFFSET_LAT"].ToString().Trim();
//sw = string.IsNullOrEmpty(sw) ? "null" : sw;
//kr = string.IsNullOrEmpty(kr) ? "null" : kr;
string comm =string.Format("insert into Students (LNG,LAT,OFFSET_LAT) values ('{0}','{1}',{2})", lng, lat, offsetLNG);
conn.Open();
string strConnection = ConfigurationManager.ConnectionStrings["Students"].ToString();
SqlConnection sqlConnection = new SqlConnection(strConnection);
sqlConnection.Open();
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.CommandText = comm;
sqlCmd.Connection = sqlConnection;
SqlDataReader sqlDataReader = sqlCmd.ExecuteReader();
i++;
sqlDataReader.Close();
}
catch (Exception erro)
{
Response.Write("错误信息:" + erro.Message);
}
finally
{
conn.Close();
}
执行没错,但是数据库没有变化。
下面是我连接的数据库:
<connectionStrings>
<add name="Students" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Students.mdf;Integrated Security=True;User Instance=True" />
</connectionStrings>