【asp.net】asp.net实现上传Excel文件并读取数据
#前台代码:使用服务端控件实现上传
<form id="form1" runat="server">
<div>
<asp:FileUpload ID="ExcelFileUpload" runat="server" />
<asp:Button ID="UploadBtn" runat="server" Text="确定上传" OnClick="UploadBtn_Click" />
</div>
</form>
#服务端代码:
protected void UploadBtn_Click(object sender, EventArgs e) { if (ExcelFileUpload.HasFile == false)//HasFile用来检查FileUpload是否有文件 { Response.Write("<script>alert('请您选择Excel文件')</script> "); return;//当无文件时,返回 } string IsXls = Path.GetExtension(ExcelFileUpload.FileName).ToString().ToLower();//System.IO.Path.GetExtension获得文件的扩展名 if (IsXls != ".xlsx" && IsXls != ".xls") { Response.Write(ExcelFileUpload.FileName); Response.Write("<script>alert('只可以选择Excel文件')</script>"); return;//当选择的不是Excel文件时,返回 } string filename = ExcelFileUpload.FileName;//获取Execle文件名 string savePath = Server.MapPath(("UploadExcel\\") + filename);//Server.MapPath 服务器上的指定虚拟路径相对应的物理文件路径 //savePath ="D:\vsproject\Projects\exceltestweb\exceltestweb\uploadfiles\test.xls" //Response.Write(savePath); DataTable ds = new DataTable(); ExcelFileUpload.SaveAs(savePath);//将文件保存到指定路径 DataTable dt = GetExcelDatatable(savePath);//读取excel数据 List<RegNumInfo> regList = ConvertDtToInfo(dt);//将datatable转为list File.Delete(savePath);//删除文件 Response.Write("<script>alert('上传文件读取数据成功!');</script>"); } /// <summary> /// 从excel文件中读取数据 /// </summary> /// <param name="fileUrl">实体文件的存储路径</param> /// <returns></returns> private static DataTable GetExcelDatatable(string fileUrl) { //支持.xls和.xlsx,即包括office2010等版本的;HDR=Yes代表第一行是标题,不是数据; string cmdText = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileUrl + "; Extended Properties=\"Excel 12.0;HDR=Yes\""; System.Data.DataTable dt = null; //建立连接 OleDbConnection conn = new OleDbConnection(cmdText); try { //打开连接 if (conn.State == ConnectionState.Broken || conn.State == ConnectionState.Closed) { conn.Open(); } System.Data.DataTable schemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null); string strSql = "select * from [Sheet1$]"; //这里指定表明为Sheet1,如果修改过表单的名称,请使用修改后的名称 OleDbDataAdapter da = new OleDbDataAdapter(strSql, conn); DataSet ds = new DataSet(); da.Fill(ds); dt = ds.Tables[0]; ; return dt; } catch (Exception exc) { throw exc; } finally { conn.Close(); conn.Dispose(); } } /// <summary> /// 将datatable转换为list集合 /// </summary> /// <param name="dt">DataTable</param> /// <returns></returns> private static List<RegNumInfo> ConvertDtToInfo(DataTable dt) { List<RegNumInfo> list = new List<RegNumInfo>(); if (dt.Rows.Count > 0) { foreach (DataRow item in dt.Rows) { RegNumInfo info = new RegNumInfo(); info.RegNum = item[0].ToString(); info.Name = item[1].ToString(); info.Period = item[2].ToString(); info.Remark = item[3].ToString(); list.Add(info); } } return list; }
public class RegNumInfo { public string RegNum { get; set; } public string Name { get; set; } public string Period { get; set; } public string Remark { get; set; } }
#注意:出现“未在本地计算机上注册“microsoft.ACE.oledb.12.0”提供程序” 的报错的解决方案
1、因为读取excel文件使用的是OleDb,如果服务器没有安装office,需要安装数据访问组件(AccessDatabaseEngine);
*适用于office2010的
Microsoft Access Database Engine 2010 Redistributable