這個操作的大致步驟是把本地文件存入到服務器端,
然后再讀取服務端的文件並且使用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); }
