我知道先把excel的数据填充到dataset里,然后再添加到数据库
我做了一个总是有错,我把代码传上来了,高手指点一下是那里的错误
帮我看看这段代码对吗??
string strPath,FileName;
strPath=File1.PostedFile.FileName;
FileName=strPath.Substring(strPath.LastIndexOf("\\")+1);
if(strPath == "")
{
Response.Write("<script>alert('请先选择文件')</script>");
return;
}
string sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + strPath + ";" +
"Extended Properties=Excel 8.0;";
OleDbConnection objConn = new OleDbConnection(sConnectionString);
try
{
objConn.Open();
OleDbCommand objCmdSelect =new OleDbCommand("SELECT * FROM [常规产品清册$]", objConn); //这里的sheet用不用带[]和里面的$阿??
OleDbDataAdapter objAdapter1 = new OleDbDataAdapter();
objAdapter1.SelectCommand = objCmdSelect;
DataSet dsolb = new DataSet();
objAdapter1.Fill(dsolb,"常规产品清册"); //这里是写sheet吗??
DataGrid1.DataSource = dsolb.Tables[0].DefaultView;
DataGrid1.DataBind();
}
catch(Exception ee)
{
Response.Write("<script>alert('请先关闭文件')</script>");
return;
}
finally
{
objConn.Close();
}
[此贴子已经被作者于2006-9-6 15:55:32编辑过]
问题解决了 谢谢大家 我把正确代码发上来了 不会的可以看看。。
string strPath = File1.PostedFile.FileName;
if(strPath == "")
{
Response.Write("<script>alert('请先选择文件')</script>");
return;
}
string sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + strPath + ";" +
"Extended Properties=Excel 8.0;";
// Create connection object by using the preceding connection string.
OleDbConnection objConn = new OleDbConnection(sConnectionString);
try
{
// Open connection with the database.
objConn.Open();
// The code to follow uses a SQL SELECT command to display the data from the worksheet.
// Create new OleDbCommand to return data from worksheet.
OleDbCommand objCmdSelect =new OleDbCommand("SELECT * FROM[常规产品清册$]", objConn);
/*************************************************************
**********************测试读取单列****************************
OleDbDataReader dr = objCmdSelect.ExecuteReader();
while(dr.Read())
{
Response.Write("产品类别"+dr[2].ToString());
}
dr.Close();
***************************************************************/
// Create new OleDbDataAdapter that is used to build a DataSet
// based on the preceding SQL SELECT statement.
OleDbDataAdapter objAdapter1 = new OleDbDataAdapter();
// Pass the Select command to the adapter.
objAdapter1.SelectCommand = objCmdSelect;
// Create new DataSet to hold information from the worksheet.
DataSet dsolb = new DataSet();
// Fill the DataSet with the information from the worksheet.
objAdapter1.Fill(dsolb);
// Bind data to DataGrid control.
DataGrid1.DataSource = dsolb;
DataGrid1.DataBind();
}
catch(Exception ee)
{
Response.Write("<script>alert('请先关闭文件')</script>");
return;
}
finally
{
// Clean up objects.
objConn.Close();
}