try
{
string filePath = ""
if (UploadFile1.Value == "")
{
Page.RegisterStartupScript("", "<script>alert('请选择要上传的文件!')
return
}
else
{
filePath = UploadFile1.Value
string name = filePath.Substring(filePath.LastIndexOf("\") + 1).ToString();
filePath = path + DateTime.Now.ToString("yyyy-MM-dd hh-mm-ss") + "_" + name;
string exp = name.Substring(name.LastIndexOf(".") + 1);
UploadFile1.PostedFile.SaveAs(filePath);
string strCon = "";
if (exp != "xls" && exp != "XLS" && exp != "xlsx" && exp != "XLSX")
{
Page.RegisterStartupScript("error", "<script>alert('文件格式不对!')
}
else
{
if (exp == "xls" || exp == "XLS")
{
strCon = "Provider=Microsoft.Jet.OleDb.4.0;Data Source=" + filePath + ";Extended Properties=Excel 8.0"
}
else
{
strCon = "Provider=Microsoft.ACE.OleDb.12.0;Data Source=" + filePath + ";Extended Properties=Excel 12.0"
}
using(OleDbConnection myConn = new OleDbConnection(strCon)){
myConn.Open()
if (name != "")
{
DataTable schemaTable = myConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" })
if (schemaTable.Rows.Count > 0)
{
string tablename = schemaTable.Rows[0]["TABLE_NAME"].ToString()
string sql = "select * from [" + tablename + "]"
OleDbDataAdapter da = new OleDbDataAdapter(sql, myConn)
DataSet ds = new DataSet()
IList<Book> PersonList = new List<Book>()
da.Fill(ds)
int r = ds.Tables[0].Rows.Count
if (r > 0)//判断Execl表是否有内容
{
for (int i = 0
{
Book entity = new Book()
entity.No = ds.Tables[0].Rows[i]["编号"].ToString().Trim()
entity.BookName = ds.Tables[0].Rows[i]["书名"].ToString().Trim()
entity.Author = ds.Tables[0].Rows[i]["作者"].ToString().Trim()
entity.Price = ds.Tables[0].Rows[i]["价格"].ToString().Trim()
_BookBO.Save(entity)
}
}
}
}
}
}
}
}
catch (Exception ex)
{
Response.Write(ex.Message)
}