2个回答
展开全部
前台页面:
<asp:FileUpload ID="FileUpload1" runat="server" Width="489px" />
<asp:Button ID="btnReadExcel" runat="server" onclick="btnReadExcel_Click"
Text="读取Excel" />
后台代码:
实现过程:先使用FileUpload1控件读取一个execl表,保存于网址根目录upload文件夹,然后从upload文件夹读取execl到gridview
protected void btnReadExcel_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
//上传Excel文件
string fileName = FileUpload1.FileName; //文件全名
string extName = fileName.Substring(fileName.LastIndexOf(".") + 1); //扩展名(文件类型)
if (extName.ToLower() != "xls")
{
Response.Write("文件格式错误,只能上传Excel 2003(扩展名为 .xls)的文件!");
return;
}
string uploadPath = Server.MapPath(@"upload");
if (!Directory.Exists(uploadPath))
{
Directory.CreateDirectory(uploadPath);
}
FileUpload1.SaveAs(uploadPath + "\\" + fileName);
//读取Excel文件
string xlsConn = "Provider=Microsoft.Jet.OLEDB.4.0;data source=" + Server.MapPath("upload\\" + fileName) + ";Extended Properties=Excel 8.0";
using (OleDbConnection conn = new OleDbConnection(xlsConn))
{
OleDbDataAdapter da = new OleDbDataAdapter("select * from [Sheet1$]", conn);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
}
}
}
<asp:FileUpload ID="FileUpload1" runat="server" Width="489px" />
<asp:Button ID="btnReadExcel" runat="server" onclick="btnReadExcel_Click"
Text="读取Excel" />
后台代码:
实现过程:先使用FileUpload1控件读取一个execl表,保存于网址根目录upload文件夹,然后从upload文件夹读取execl到gridview
protected void btnReadExcel_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
//上传Excel文件
string fileName = FileUpload1.FileName; //文件全名
string extName = fileName.Substring(fileName.LastIndexOf(".") + 1); //扩展名(文件类型)
if (extName.ToLower() != "xls")
{
Response.Write("文件格式错误,只能上传Excel 2003(扩展名为 .xls)的文件!");
return;
}
string uploadPath = Server.MapPath(@"upload");
if (!Directory.Exists(uploadPath))
{
Directory.CreateDirectory(uploadPath);
}
FileUpload1.SaveAs(uploadPath + "\\" + fileName);
//读取Excel文件
string xlsConn = "Provider=Microsoft.Jet.OLEDB.4.0;data source=" + Server.MapPath("upload\\" + fileName) + ";Extended Properties=Excel 8.0";
using (OleDbConnection conn = new OleDbConnection(xlsConn))
{
OleDbDataAdapter da = new OleDbDataAdapter("select * from [Sheet1$]", conn);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
}
}
}
展开全部
excel本身是个数据库,可以直接用select 提取, 然后放入dt
追问
有木有详细点的代码啊??是成绩表(学号,课程号,分数)。将excel表导入。。非常感谢啊
追答
本机建立odbc ,去连接excel文件, 然后在程序中用odbc连接方式连接数据库,可以直接select * from [$sheet1] ,好像是这样子的, 执行sql语句,放入datatable ,绑定gv,不就ol
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询