Code
protected void Button1_Click(object sender, EventArgs e)
{
if (myFile.PostedFile.FileName != "")
{
//上传文件的绝对路径
string sFile = myFile.PostedFile.FileName;
//获取文件全名
sFile = sFile.Substring(sFile.LastIndexOf("\\") + 1);
//获取后缀名
sFile = sFile.Substring(sFile.LastIndexOf("."));
if (sFile.ToLower() != ".xls")
{
Response.Write("请选择Excel文件!");
Response.End();
}
//为了防止重名,获得日期为文件名年月日时分秒毫秒
string datatime = System.DateTime.Now.ToString("yyyMMddHHmmssffff");
//上传后文件的新名
sFile = datatime + sFile;
//AppDomain.CurrentDomain.BaseDirectory.ToString() 获取此项目的根目录
//上传文件
myFile.SaveAs(Server.MapPath(".") + "\\" + sFile);
DataSet ds = GetExcelContent(Server.MapPath(".") + "\\" + sFile);
this.myGridView.DataSource = ds;
this.myGridView.DataBind();
}
}
//读取EXCEL到DATASET代码:
public DataSet GetExcelContent(string filepath)
{
string strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filepath + ";Extended Properties='Excel 8.0;HDR=No;IMEX=1'";
OleDbConnection myConn = new OleDbConnection(strCon);
string strCom = "SELECT * FROM [Sheet1$]";
myConn.Open();
OleDbDataAdapter myCommand = new OleDbDataAdapter(strCom, myConn);
//创建一个DataSet对象
DataSet myDataSet = new DataSet();
//得到自己的DataSet对象
myCommand.Fill(myDataSet);
//关闭此数据链接
myConn.Close();
return myDataSet;
}
protected void Button1_Click(object sender, EventArgs e)
{
if (myFile.PostedFile.FileName != "")
{
//上传文件的绝对路径
string sFile = myFile.PostedFile.FileName;
//获取文件全名
sFile = sFile.Substring(sFile.LastIndexOf("\\") + 1);
//获取后缀名
sFile = sFile.Substring(sFile.LastIndexOf("."));
if (sFile.ToLower() != ".xls")
{
Response.Write("请选择Excel文件!");
Response.End();
}
//为了防止重名,获得日期为文件名年月日时分秒毫秒
string datatime = System.DateTime.Now.ToString("yyyMMddHHmmssffff");
//上传后文件的新名
sFile = datatime + sFile;
//AppDomain.CurrentDomain.BaseDirectory.ToString() 获取此项目的根目录
//上传文件
myFile.SaveAs(Server.MapPath(".") + "\\" + sFile);
DataSet ds = GetExcelContent(Server.MapPath(".") + "\\" + sFile);
this.myGridView.DataSource = ds;
this.myGridView.DataBind();
}
}
//读取EXCEL到DATASET代码:
public DataSet GetExcelContent(string filepath)
{
string strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filepath + ";Extended Properties='Excel 8.0;HDR=No;IMEX=1'";
OleDbConnection myConn = new OleDbConnection(strCon);
string strCom = "SELECT * FROM [Sheet1$]";
myConn.Open();
OleDbDataAdapter myCommand = new OleDbDataAdapter(strCom, myConn);
//创建一个DataSet对象
DataSet myDataSet = new DataSet();
//得到自己的DataSet对象
myCommand.Fill(myDataSet);
//关闭此数据链接
myConn.Close();
return myDataSet;
}
这样就把数据导入到DataSet中了
从DataSet中将数据导入到库里貌似就好操作了