这个操作的大致步骤是把本地文件存入到服务器端,
然后再读取服务端的文件并且使用NPOI这个第三方的插件去读取文件导入到数据库批量插入
需要注意的是,前端需要使用form包裹type=file的文件标签,并且文件标签需要有name属性,否则后台无法获取,在一个就是form需要含有enctype="multipart/form-data"属性,
对于input过滤其他非excel的文件,可以添加如下属性:accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
HTML:
<form id="form" class="form-horizontal" enctype="multipart/form-data"> <div class="form-group"> <label for="txt_signInTitleOfDetail">选择文件</label> <input type="file" name="file" class="form-control" accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" /> </div> <input type="button" class="btn btn-primary" value="保存" id="btn_Save"> </form>
JS:
//这里的HTMLFormElement是强制转换的写法,因为是typescript所以不强制转换的话编译不能通过 var myForm = <HTMLFormElement>$('#你的要提交的form的ID')[0]; var formData = new FormData(myForm);//和后台联通让后台接受form的系统类 //获取文件名 var filePath = $('#txt_upload').val(); var fileName = filePath.substring(filePath.lastIndexOf('\') + 1); formData.append('fileName', fileName); $('#waring').text("操作中,请等待"); $.ajax({ url: '/Home/后台的导入方法', type: 'POST', cache: false, data: formData, processData: false, contentType: false }).done(function (res) { //批量导入后刷新页面 $('#waring').text(res.message); }).fail(function (res) { $('#waring').text("导入数据失败"); });
后台:
public JsonResult 你的方法() { var httpRequest = HttpContext.Request; string fileName = string.Format("{0}_{1}", DateTime.Now.ToString("yyyyMMddHHmmss"), httpRequest.Form["fileName"].ToString()); //文件夹 string dir = Server.MapPath("~/temp"); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } //文件全路径,获取了本地的文件路径 string filePath = Path.Combine(dir, fileName); foreach (string key in httpRequest.Files) // 文件键 { var postedFile = httpRequest.Files[key]; // 获取文件键对应的文件对象 postedFile.SaveAs(filePath); } //// 读取Excel文件,导入数据 ExcelToDB(filePath); return Json(new { status = true, message = "导入成功!" }); } private void ExcelToDB(string filePath) { FileStream fs = null; IWorkbook workbook = null; ISheet sheet = null; IRow row = null; //ICell cell = null; int startRow = 1; try { using (fs = System.IO.File.OpenRead(filePath)) { // 2007版本 if (filePath.IndexOf(".xlsx") > 0) workbook = new XSSFWorkbook(fs); // 2003版本 else if (filePath.IndexOf(".xls") > 0) workbook = new HSSFWorkbook(fs); if (workbook != null) { workbook.MissingCellPolicy = MissingCellPolicy.RETURN_BLANK_AS_NULL; //sheet = workbook.GetSheetAt(0);//读取第一个sheet,当然也可以循环读取每个sheet sheet = workbook.GetSheet("Sheet1"); if (sheet != null) { int rowCount = sheet.LastRowNum;//总行数 if (rowCount > 0) { IRow firstRow = sheet.GetRow(0);//第一行 int cellCount = firstRow.LastCellNum;//列数 WriteData(sheet, row, startRow, rowCount); } else { throw new Exception("无信息"); } } else { throw new Exception("没有找到Sheet1"); } } else { throw new Exception("加载Excel失败"); } } } catch (Exception ex) { if (fs != null) { fs.Close(); } throw ex; } } /// <summary> /// 从excel写入登记表 /// </summary> /// <param name="sheet"></param> /// <param name="row"></param> /// <param name="startRow"></param> /// <param name="rowCount"></param> /// <param name="isCover"></param> private void WriteData(ISheet sheet, IRow row, int startRow, int rowCount) { List<你的插入类> 你的插入类 = new List<你的插入类>(); string Title = string.Empty; string Time = string.Empty; string EndTime = string.Empty; string Range = string.Empty; //填充行 for (int i = startRow; i <= rowCount; ++i) { row = sheet.GetRow(i); if (row == null) continue; try { //读取一行每个字段值 Title = row.GetCell(0, MissingCellPolicy.CREATE_NULL_AS_BLANK).ToString(); // Time = row.GetCell(1, MissingCellPolicy.CREATE_NULL_AS_BLANK).ToString();// EndTime = row.GetCell(2, MissingCellPolicy.CREATE_NULL_AS_BLANK).ToString();// taskType = 1;// signInRange = row.GetCell(3, MissingCellPolicy.CREATE_NULL_AS_BLANK).ToString();// //没有信息,直接跳过 if (string.IsNullOrEmpty(Title) || string.IsNullOrEmpty(Time) || string.IsNullOrEmpty(EndTime)) { continue; } info item = new info() { 读取的行在这里和实体类赋值 }; list.Add(item); } catch (Exception ex) { } } //批量插入 Dal.BatchInsert(list); }