頁面代碼:web
<form id="form1" enctype="multipart/form-data"> <div style="float:right"> <button type="button" class="btn btn-primary" onclick="$('#fileUpload').click()" id="reviewFile">瀏覽</button> <button class="btn btn-primary" type="button" style="margin-left:5px;height:30px;" id="dataExport">批量導入</button> <input type="button" class="btn btn-primary" style="margin-left:5px;height:30px;" id="downLoad" value="下載模板"> </div> <div style="float:right;margin-top:5px"> <input id="fileUpload" name="fileUpload" type="file" style="display:none" /> <input id="fileText" type="text" class="form-control" disabled /> </div> <script> $("#fileUpload").change(function () { $("#fileText").val($(this).val()); }) </script> </form>
js代碼:ajax
//導入excel數據 $("#dataExport").click(function () { var formData = new FormData($('form')[0]); $.ajax({ url: '/BaseInfoPage/Upload', type: 'POST', xhr: function () { return $.ajaxSettings.xhr(); }, data: formData, cache: false, contentType: false, processData: false, success: function (data) { if (data == "導入成功!") { layer.msg(data, { icon: 1, time: 5000 }, function () { location.reload(); //刷新父頁面 第二個參數設置msg顯示的時間長短 }); } else { layer.msg(data, { icon: 0, time: 5000 }, function () { return; }); } }, error: function (e) { layer.msg(e, { icon: 0, time: 5000 }, function () { return; }); } }); })
c#後臺代碼:sql
public string Upload(HttpPostedFileBase fileUpload) { if (fileUpload == null) { return "文件爲空"; } string fileExtension = Path.GetExtension(fileUpload.FileName);//獲取文件名後綴 try { //判斷文件類型 if (".xls" == fileExtension || ".xlsx" == fileExtension) { //將硬盤路徑轉化爲服務器路徑的文件流 //string fileName = Path.Combine(Request.MapPath("~/ExcelTemplate"), Path.GetFileName(fileUpload.FileName)); string fileName = fileUpload.FileName; string filePath = ""; filePath = CSysCfg.exFilePath; if (!Directory.Exists(filePath)) { Directory.CreateDirectory(filePath); } //保存模板到服務器 fileUpload.SaveAs(filePath + "\\" + fileName); //從NPOI讀取到的Excel的數據,保存到excelTable裏 DataTable excelTable = new DataTable(); excelTable = GetExcelDataTable(filePath + "\\" + fileName);//自定義方法 //把表的中文表頭轉換成數據庫表中對應的英文 DataTable dbdata = new DataTable(); dbdata.Columns.Add("ltl_Id"); dbdata.Columns.Add("ltl_PlateId"); dbdata.Columns.Add("ltl_StarteTime"); dbdata.Columns.Add("ltl_EndTime"); for (int i = 0; i < excelTable.Rows.Count; i++) { DataRow dr = excelTable.Rows[i]; DataRow dr_ = dbdata.NewRow(); dr_["ltl_Id"] = dr["申請編號"]; dr_["ltl_PlateId"] = dr["車牌號碼"]; dr_["ltl_StarteTime"] = dr["開始日期"]; dr_["ltl_EndTime"] = dr["結束日期"]; dbdata.Rows.Add(dr_); } RemoveEmpty(dbdata);//自定義方法 //獲取鏈接字符串,調用批量插入數據庫的方法 需更改web.config添加配置 string constr = System.Configuration.ConfigurationManager.AppSettings["exportData"]; SqlBulkCopyByDatatable(constr, "LargeTransportLicense", dbdata);//自定義方法(鏈接字符串,表名,數據) return "導入成功!"; } else { return "只能夠選擇Excel文件!"; } } catch { return "導入失敗!"; } } // 從Excel中獲取數據到DataTable public static DataTable GetExcelDataTable(string filePath) { IWorkbook Workbook; DataTable table = new DataTable(); try { using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { //XSSFWorkbook 適用XLSX格式,HSSFWorkbook 適用XLS格式 string fileExt = Path.GetExtension(filePath).ToLower(); if (fileExt == ".xls") { Workbook = new HSSFWorkbook(fileStream); } else if (fileExt == ".xlsx") { Workbook = new XSSFWorkbook(fileStream); } else { Workbook = null; } } //定位在第一個sheet ISheet sheet = Workbook.GetSheetAt(0); //第一行爲標題行 IRow headerRow = sheet.GetRow(1); int cellCount = headerRow.LastCellNum;// 是當前行的總列數 int rowCount = sheet.LastRowNum;////LastRowNum 是當前表的總行數-1(注意) //循環添加標題列 for (int i = headerRow.FirstCellNum; i < cellCount; i++) { DataColumn column = new DataColumn(headerRow.GetCell(i).StringCellValue); table.Columns.Add(column); } List<string> regionName = new List<string>(); //數據 for (int i = (sheet.FirstRowNum + 2); i <= rowCount; i++) { IRow row = sheet.GetRow(i); DataRow dataRow = table.NewRow(); if (row != null) { for (int j = row.FirstCellNum; j < cellCount; j++) { if (row.GetCell(j) != null) { dataRow[j] = GetCellValue2(row.GetCell(j)); } } } table.Rows.Add(dataRow); } } catch (Exception ex) { throw ex; } return table; } //數據類型判斷 方式一 private static string GetCellValue(NPOI.SS.UserModel.ICell cell) { if (cell == null) { return string.Empty; } else { switch (cell.CellType) { case CellType.Blank: return string.Empty; case CellType.Boolean: return cell.BooleanCellValue.ToString(); case CellType.Error: return cell.ErrorCellValue.ToString(); case CellType.Numeric://數值 case CellType.Unknown: default: return cell.ToString(); case CellType.String: return cell.StringCellValue; case CellType.Formula://公式 try { HSSFFormulaEvaluator e = new HSSFFormulaEvaluator(cell.Sheet.Workbook); e.EvaluateInCell(cell); return cell.ToString(); } catch { return cell.NumericCellValue.ToString(); } } } } //數據類型判斷,並設置爲對應的數據類型 方式二 public static object GetCellValue2(NPOI.SS.UserModel.ICell cell) { object value = null; if (cell == null) { value = 0; } try { if (cell.CellType != CellType.Blank) { switch (cell.CellType) { case CellType.Blank: value = string.Empty; break; case CellType.Numeric: // 日期 if (DateUtil.IsCellDateFormatted(cell)) { value = cell.DateCellValue; } else { // 數值 value = cell.NumericCellValue; } break; case CellType.Boolean: // Boolean type value = cell.BooleanCellValue; break; case CellType.Formula: value = cell.CellFormula; break; default: // String type value = cell.StringCellValue; break; } } else { value = 0; } } catch (Exception) { value = 0; } return value; } /// <summary> /// 大數據插入 /// </summary> /// <param name="connectionString">目標庫鏈接</param> /// <param name="TableName">目標表</param> /// <param name="dtSelect">來源數據</param> public static void SqlBulkCopyByDatatable(string connectionString, string TableName, DataTable dtSelect) { using (SqlConnection conn = new SqlConnection(connectionString)) { using (SqlBulkCopy sqlbulkcopy = new SqlBulkCopy(connectionString, SqlBulkCopyOptions.UseInternalTransaction)) { try { sqlbulkcopy.DestinationTableName = TableName; sqlbulkcopy.BatchSize = 20000; sqlbulkcopy.BulkCopyTimeout = 0;//不限時間 for (int i = 0; i < dtSelect.Columns.Count; i++) { sqlbulkcopy.ColumnMappings.Add(dtSelect.Columns[i].ColumnName, dtSelect.Columns[i].ColumnName); } sqlbulkcopy.WriteToServer(dtSelect); } catch (System.Exception ex) { throw ex; } } } } //在導入Excel數據的時候,有時候會有空行,用RemoveEmpty方法去空 protected void RemoveEmpty(DataTable dt) { List<DataRow> removelist = new List<DataRow>(); for (int i = 0; i < dt.Rows.Count; i++) { bool IsNull = true; for (int j = 0; j < dt.Columns.Count; j++) { if (!string.IsNullOrEmpty(dt.Rows[i][j].ToString().Trim())) { IsNull = false; } } if (IsNull) { removelist.Add(dt.Rows[i]); } } for (int i = 0; i < removelist.Count; i++) { dt.Rows.Remove(removelist[i]); } }
注:此方法需在web.config中添加配置數據庫
<appSettings> <add key="exportData" value="server=xxx;database=xx;uid=xxx;pwd=xxx" /> </appSettings>