java項目中Excel文件的導入導出javascript
Excel 工具類html
package cn.cmodes.common.utils.poi; import cn.cmodes.common.utils.DateUtils; import cn.cmodes.common.utils.DictUtils; import cn.cmodes.common.utils.StringUtils; import cn.cmodes.framework.aspectj.lang.annotation.Excel; import cn.cmodes.framework.config.SystemConfig; import cn.cmodes.framework.web.domain.AjaxResult; import org.apache.poi.hssf.usermodel.*; import org.apache.poi.hssf.util.HSSFColor.HSSFColorPredefined; import org.apache.poi.ss.usermodel.*; import org.apache.poi.ss.util.CellRangeAddressList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.lang.reflect.Field; import java.net.URLEncoder; import java.text.SimpleDateFormat; import java.util.*; /** * Excel相關處理 */ public class ExcelUtil<T> { private static final Logger log = LoggerFactory.getLogger(ExcelUtil.class); public Class<T> clazz; public ExcelUtil(Class<T> clazz) { this.clazz = clazz; } /** * 對excel表單默認第一個索引名轉換成list * * @param input 輸入流 * @return 轉換後集合 */ public List<T> importExcel(InputStream input) throws Exception { return importExcel(StringUtils.EMPTY, input); } /** * 對excel表單指定表格索引名轉換成list * * @param sheetName 表格索引名 * @param input 輸入流 * @return 轉換後集合 */ public List<T> importExcel(String sheetName, InputStream input) throws Exception { List<T> list = new ArrayList<T>(); Workbook workbook = WorkbookFactory.create(input); Sheet sheet = null; if (StringUtils.isNotEmpty(sheetName)) { // 若是指定sheet名,則取指定sheet中的內容. sheet = workbook.getSheet(sheetName); } else { // 若是傳入的sheet名不存在則默認指向第1個sheet. sheet = workbook.getSheetAt(0); } if (sheet == null) { throw new IOException("文件sheet不存在"); } int rows = sheet.getPhysicalNumberOfRows(); if (rows > 0) { // 默認序號 int serialNum = 0; // 有數據時才處理 獲得類的全部field. Field[] allFields = clazz.getDeclaredFields(); // 定義一個map用於存放列的序號和field. Map<Integer, Field> fieldsMap = new HashMap<Integer, Field>(); for (int col = 0; col < allFields.length; col++) { Field field = allFields[col]; // 將有註解的field存放到map中. if (field.isAnnotationPresent(Excel.class)) { // 設置類的私有字段屬性可訪問. field.setAccessible(true); fieldsMap.put(++serialNum, field); } } for (int i = 1; i < rows; i++) { // 從第2行開始取數據,默認第一行是表頭. Row row = sheet.getRow(i); int cellNum = serialNum; T entity = null; for (int j = 0; j < cellNum; j++) { Cell cell = row.getCell(j); if (cell == null) { continue; } else { // 先設置Cell的類型,而後就能夠把純數字做爲String類型讀進來了 row.getCell(j).setCellType(CellType.STRING); cell = row.getCell(j); } String c = cell.getStringCellValue(); if (StringUtils.isEmpty(c)) { continue; } // 若是不存在實例則新建. entity = (entity == null ? clazz.newInstance() : entity); // 從map中獲得對應列的field. Field field = fieldsMap.get(j + 1); // 取得類型,並根據對象類型設置值. Class<?> fieldType = field.getType(); if (String.class == fieldType) { field.set(entity, String.valueOf(c)); } else if ((Integer.TYPE == fieldType) || (Integer.class == fieldType)) { field.set(entity, Integer.parseInt(c)); } else if ((Long.TYPE == fieldType) || (Long.class == fieldType)) { field.set(entity, Long.valueOf(c)); } else if ((Float.TYPE == fieldType) || (Float.class == fieldType)) { field.set(entity, Float.valueOf(c)); } else if ((Short.TYPE == fieldType) || (Short.class == fieldType)) { field.set(entity, Short.valueOf(c)); } else if ((Double.TYPE == fieldType) || (Double.class == fieldType)) { field.set(entity, Double.valueOf(c)); } else if (Character.TYPE == fieldType) { if ((c != null) && (c.length() > 0)) { field.set(entity, Character.valueOf(c.charAt(0))); } } else if (java.util.Date.class == fieldType) { if (cell.getCellTypeEnum() == CellType.NUMERIC) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); cell.setCellValue(sdf.format(cell.getNumericCellValue())); c = sdf.format(cell.getNumericCellValue()); } else { c = cell.getStringCellValue(); } } else if (java.math.BigDecimal.class == fieldType) { c = cell.getStringCellValue(); } } if (entity != null) { list.add(entity); } } } return list; } /** * 對list數據源將其裏面的數據導入到excel表單 * * @param list 導出數據集合 * @param sheetName 工做表的名稱 * @return 結果 */ public AjaxResult exportExcel(List<T> list, String sheetName) { OutputStream out = null; HSSFWorkbook workbook = null; try { // 獲得全部定義字段 Field[] allFields = clazz.getDeclaredFields(); List<Field> fields = new ArrayList<Field>(); // 獲得全部field並存放到一個list中. for (Field field : allFields) { if (field.isAnnotationPresent(Excel.class)) { fields.add(field); } } // 產生工做薄對象 workbook = new HSSFWorkbook(); // excel2003中每一個sheet中最多有65536行 int sheetSize = 65536; // 取出一共有多少個sheet. double sheetNo = Math.ceil(list.size() / sheetSize); for (int index = 0; index <= sheetNo; index++) { // 產生工做表對象 HSSFSheet sheet = workbook.createSheet(); if (sheetNo == 0) { workbook.setSheetName(index, sheetName); } else { // 設置工做表的名稱. workbook.setSheetName(index, sheetName + index); } HSSFRow row; HSSFCell cell; // 產生單元格 // 產生一行 row = sheet.createRow(0); // 寫入各個字段的列頭名稱 for (int i = 0; i < fields.size(); i++) { Field field = fields.get(i); Excel attr = field.getAnnotation(Excel.class); // 建立列 cell = row.createCell(i); // 設置列中寫入內容爲String類型 cell.setCellType(CellType.STRING); HSSFCellStyle cellStyle = workbook.createCellStyle(); cellStyle.setAlignment(HorizontalAlignment.CENTER); cellStyle.setVerticalAlignment(VerticalAlignment.CENTER); if (attr.name().indexOf("注:") >= 0) { HSSFFont font = workbook.createFont(); font.setColor(HSSFFont.COLOR_RED); cellStyle.setFont(font); cellStyle.setFillForegroundColor(HSSFColorPredefined.YELLOW.getIndex()); sheet.setColumnWidth(i, 6000); } else { HSSFFont font = workbook.createFont(); // 粗體顯示 font.setBold(true); // 選擇須要用到的字體格式 cellStyle.setFont(font); cellStyle.setFillForegroundColor(HSSFColorPredefined.LIGHT_YELLOW.getIndex()); // 設置列寬 sheet.setColumnWidth(i, 3766); } cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); cellStyle.setWrapText(true); cell.setCellStyle(cellStyle); // 寫入列名 cell.setCellValue(attr.name()); // 若是設置了提示信息則鼠標放上去提示. if (StringUtils.isNotEmpty(attr.prompt())) { // 這裏默認設了2-101列提示. setHSSFPrompt(sheet, "", attr.prompt(), 1, 100, i, i); } // 若是設置了combo屬性則本列只能選擇不能輸入 if (attr.combo().length > 0) { // 這裏默認設了2-101列只能選擇不能輸入. setHSSFValidation(sheet, attr.combo(), 1, 100, i, i); } } int startNo = index * sheetSize; int endNo = Math.min(startNo + sheetSize, list.size()); // 寫入各條記錄,每條記錄對應excel表中的一行 HSSFCellStyle cs = workbook.createCellStyle(); cs.setAlignment(HorizontalAlignment.CENTER); cs.setVerticalAlignment(VerticalAlignment.CENTER); for (int i = startNo; i < endNo; i++) { row = sheet.createRow(i + 1 - startNo); // 獲得導出對象. T vo = (T) list.get(i); for (int j = 0; j < fields.size(); j++) { // 得到field. Field field = fields.get(j); // 設置實體類私有屬性可訪問 field.setAccessible(true); Excel attr = field.getAnnotation(Excel.class); try { // 根據Excel中設置狀況決定是否導出,有些狀況須要保持爲空,但願用戶填寫這一列. if (attr.isExport()) { // 建立cell cell = row.createCell(j); cell.setCellType(CellType.NUMERIC); try { if (vo == null) { // 若是數據存在就填入,不存在填入空格. cell.setCellValue(""); } else { if (StringUtils.isNotBlank(attr.dictType())) { cell.setCellValue(field.get(vo) == null ? "" : DictUtils.getDictName(field.get(vo).toString(), attr.dictType(), "")); } else { Object val = field.get(vo); // 若是數據存在就填入,不存在填入空格. String cellFormatString = "@"; if (val instanceof String) { cell.setCellValue((String) val); cell.setCellType(CellType.STRING); } else if (val instanceof Integer) { cell.setCellValue((Integer) val); cellFormatString = "0"; } else if (val instanceof Long) { cell.setCellValue((Long) val); cellFormatString = "0"; } else if (val instanceof Double) { cell.setCellValue((Double) val); cellFormatString = "0.00"; } else if (val instanceof Float) { cell.setCellValue((Float) val); cellFormatString = "0.00"; } else if (val instanceof Date) { cell.setCellValue(DateUtils.parseDateToStr("yyyy-MM-dd HH:mm", (Date) val)); cellFormatString = "yyyy-MM-dd HH:mm"; cell.setCellType(CellType.STRING); } else { cell.setCellType(CellType.STRING); cell.setCellValue(field.get(vo) == null ? "" : String.valueOf(field.get(vo))); } cs.setDataFormat(workbook.createDataFormat().getFormat(cellFormatString)); } } cell.setCellStyle(cs); } catch (Exception e) { e.printStackTrace(); } } } catch (Exception e) { log.error("導出Excel失敗{}", e.getMessage()); } } } } String filename = encodingFilename(sheetName); out = new FileOutputStream(getAbsoluteFile(filename)); workbook.write(out); return AjaxResult.success(filename); } catch (Exception e) { log.error("導出Excel異常{}", e.getMessage()); return AjaxResult.error("導出Excel失敗,請聯繫網站管理員!"); } finally { if (workbook != null) { try { workbook.close(); } catch (IOException e1) { e1.printStackTrace(); } } if (out != null) { try { out.close(); } catch (IOException e1) { e1.printStackTrace(); } } } } /** * 對list數據源將其裏面的數據導入到excel表單 * * @param list 導出數據集合 * @param sheetName 工做表的名稱 * @return 結果 */ public void exportExcel(List<T> list, String sheetName, HttpServletResponse response) { OutputStream out = null; HSSFWorkbook workbook = null; try { // 獲得全部定義字段 Field[] allFields = clazz.getDeclaredFields(); List<Field> fields = new ArrayList<Field>(); // 獲得全部field並存放到一個list中. for (Field field : allFields) { if (field.isAnnotationPresent(Excel.class)) { fields.add(field); } } // 產生工做薄對象 workbook = new HSSFWorkbook(); // excel2003中每一個sheet中最多有65536行 int sheetSize = 65536; // 取出一共有多少個sheet. double sheetNo = Math.ceil(list.size() / sheetSize); for (int index = 0; index <= sheetNo; index++) { // 產生工做表對象 HSSFSheet sheet = workbook.createSheet(); if (sheetNo == 0) { workbook.setSheetName(index, sheetName); } else { // 設置工做表的名稱. workbook.setSheetName(index, sheetName + index); } HSSFRow row; HSSFCell cell; // 產生單元格 // 產生一行 row = sheet.createRow(0); // 寫入各個字段的列頭名稱 for (int i = 0; i < fields.size(); i++) { Field field = fields.get(i); Excel attr = field.getAnnotation(Excel.class); // 建立列 cell = row.createCell(i); // 設置列中寫入內容爲String類型 cell.setCellType(CellType.STRING); HSSFCellStyle cellStyle = workbook.createCellStyle(); cellStyle.setAlignment(HorizontalAlignment.CENTER); cellStyle.setVerticalAlignment(VerticalAlignment.CENTER); if (attr.name().indexOf("注:") >= 0) { HSSFFont font = workbook.createFont(); font.setColor(HSSFFont.COLOR_RED); cellStyle.setFont(font); cellStyle.setFillForegroundColor(HSSFColorPredefined.YELLOW.getIndex()); sheet.setColumnWidth(i, 6000); } else { HSSFFont font = workbook.createFont(); // 粗體顯示 font.setBold(true); // 選擇須要用到的字體格式 cellStyle.setFont(font); cellStyle.setFillForegroundColor(HSSFColorPredefined.LIGHT_YELLOW.getIndex()); // 設置列寬 sheet.setColumnWidth(i, 3766); } cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); cellStyle.setWrapText(true); cell.setCellStyle(cellStyle); // 寫入列名 cell.setCellValue(attr.name()); // 若是設置了提示信息則鼠標放上去提示. if (StringUtils.isNotEmpty(attr.prompt())) { // 這裏默認設了2-101列提示. setHSSFPrompt(sheet, "", attr.prompt(), 1, 100, i, i); } // 若是設置了combo屬性則本列只能選擇不能輸入 if (attr.combo().length > 0) { // 這裏默認設了2-101列只能選擇不能輸入. setHSSFValidation(sheet, attr.combo(), 1, 100, i, i); } } int startNo = index * sheetSize; int endNo = Math.min(startNo + sheetSize, list.size()); // 寫入各條記錄,每條記錄對應excel表中的一行 HSSFCellStyle cs = workbook.createCellStyle(); cs.setAlignment(HorizontalAlignment.CENTER); cs.setVerticalAlignment(VerticalAlignment.CENTER); for (int i = startNo; i < endNo; i++) { row = sheet.createRow(i + 1 - startNo); // 獲得導出對象. T vo = (T) list.get(i); for (int j = 0; j < fields.size(); j++) { // 得到field. Field field = fields.get(j); // 設置實體類私有屬性可訪問 field.setAccessible(true); Excel attr = field.getAnnotation(Excel.class); try { // 根據Excel中設置狀況決定是否導出,有些狀況須要保持爲空,但願用戶填寫這一列. if (attr.isExport()) { // 建立cell cell = row.createCell(j); cell.setCellType(CellType.NUMERIC); try { if (vo == null) { // 若是數據存在就填入,不存在填入空格. cell.setCellValue(""); } else { if (StringUtils.isNotBlank(attr.dictType())) { cell.setCellValue(field.get(vo) == null ? "" : DictUtils.getDictName(field.get(vo).toString(), attr.dictType(), "")); } else { Object val = field.get(vo); // 若是數據存在就填入,不存在填入空格. String cellFormatString = "@"; if (val instanceof String) { cell.setCellValue((String) val); cell.setCellType(CellType.STRING); } else if (val instanceof Integer) { cell.setCellValue((Integer) val); cellFormatString = "0"; } else if (val instanceof Long) { cell.setCellValue((Long) val); cellFormatString = "0"; } else if (val instanceof Double) { cell.setCellValue((Double) val); cellFormatString = "0.00"; } else if (val instanceof Float) { cell.setCellValue((Float) val); cellFormatString = "0.00"; } else if (val instanceof Date) { cell.setCellValue(DateUtils.parseDateToStr("yyyy-MM-dd HH:mm", (Date) val)); cellFormatString = "yyyy-MM-dd HH:mm"; cell.setCellType(CellType.STRING); } else { cell.setCellType(CellType.STRING); cell.setCellValue(field.get(vo) == null ? "" : String.valueOf(field.get(vo))); } cs.setDataFormat(workbook.createDataFormat().getFormat(cellFormatString)); } } cell.setCellStyle(cs); } catch (Exception e) { e.printStackTrace(); } } } catch (Exception e) { log.error("導出Excel失敗{}", e.getMessage()); } } } } String filename = encodingFilename(sheetName); filename = URLEncoder.encode(filename,"UTF-8"); out = new FileOutputStream(getAbsoluteFile(filename)); response.addHeader("Content-Disposition", "attachment;filename=" + filename); //1.設置文件ContentType類型,這樣設置,會自動判斷下載文件類型 response.setContentType("multipart/form-data"); out = response.getOutputStream(); workbook.write(out); } catch (Exception e) { log.error("導出Excel異常{}", e.getMessage()); } finally { if (workbook != null) { try { workbook.close(); } catch (IOException e1) { e1.printStackTrace(); } } if (out != null) { try { out.close(); } catch (IOException e1) { e1.printStackTrace(); } } } } /** * 設置單元格上提示 * * @param sheet 要設置的sheet. * @param promptTitle 標題 * @param promptContent 內容 * @param firstRow 開始行 * @param endRow 結束行 * @param firstCol 開始列 * @param endCol 結束列 * @return 設置好的sheet. */ public static HSSFSheet setHSSFPrompt(HSSFSheet sheet, String promptTitle, String promptContent, int firstRow, int endRow, int firstCol, int endCol) { // 構造constraint對象 DVConstraint constraint = DVConstraint.createCustomFormulaConstraint("DD1"); // 四個參數分別是:起始行、終止行、起始列、終止列 CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol); // 數據有效性對象 HSSFDataValidation dataValidationView = new HSSFDataValidation(regions, constraint); dataValidationView.createPromptBox(promptTitle, promptContent); sheet.addValidationData(dataValidationView); return sheet; } /** * 設置某些列的值只能輸入預製的數據,顯示下拉框. * * @param sheet 要設置的sheet. * @param textlist 下拉框顯示的內容 * @param firstRow 開始行 * @param endRow 結束行 * @param firstCol 開始列 * @param endCol 結束列 * @return 設置好的sheet. */ public static HSSFSheet setHSSFValidation(HSSFSheet sheet, String[] textlist, int firstRow, int endRow, int firstCol, int endCol) { // 加載下拉列表內容 DVConstraint constraint = DVConstraint.createExplicitListConstraint(textlist); // 設置數據有效性加載在哪一個單元格上,四個參數分別是:起始行、終止行、起始列、終止列 CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol); // 數據有效性對象 HSSFDataValidation dataValidationList = new HSSFDataValidation(regions, constraint); sheet.addValidationData(dataValidationList); return sheet; } /** * 編碼文件名 */ public String encodingFilename(String filename) { return filename + ".xls"; } /** * 獲取下載路徑 * * @param filename 文件名稱 */ public String getAbsoluteFile(String filename) { String downloadPath = SystemConfig.getProfile() + filename; File desc = new File(downloadPath); if (!desc.getParentFile().exists()) { desc.getParentFile().mkdirs(); } return downloadPath; } }
VO 實體類: @Excel(name = " ")//標註要寫在的字段java
package cn.cmodes.project.module.scholar.domain; import cn.cmodes.framework.aspectj.lang.annotation.Excel; import cn.cmodes.framework.web.domain.BaseEntity; import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import org.springframework.format.annotation.DateTimeFormat; import java.util.Date; /** * 學者(學人)表 t_scholar * * @author dqj * @date 2019-02-25 */ @Data @EqualsAndHashCode(callSuper = true) @NoArgsConstructor public class Scholar extends BaseEntity { private static final long serialVersionUID = 1L; /** * 主鍵 */ private String id; /** * 建立時間 */ @JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd") @DateTimeFormat(pattern = "yyyy-MM-dd") private Date createTime; /** * 更新時間 */ @JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd") @DateTimeFormat(pattern = "yyyy-MM-dd") private Date updateTime; /** * 學人姓名 */ @Excel(name = "學人姓名") private String title; /** * 首字母 */ @Excel(name = "首字母") private String initial; /** * 性別 */ @Excel(name = "性別") private String gender; /** * 國籍 */ @Excel(name = "國籍") private String nationality; /** * 民族 */ @Excel(name = "民族") private String nation; /** * 出生年月 */ @Excel(name = "出生年月") private String birth; /** * 畢業院校 */ @Excel(name = "畢業院校") private String university; /** * 工做單位 */ @Excel(name = "工做單位") private String jobAddress; /** * 照片 */ @Excel(name = "照片") private String photo; /** * 簡歷 */ @Excel(name = "簡歷") private String resume; /** * 任職狀況 */ @Excel(name = "任職狀況") private String positionStatus; /** * 職稱 */ @Excel(name = "職稱") private String position; /** * 研究領域 */ @Excel(name = "研究領域") private String researchField; /** * 承擔課題 */ @Excel(name = "承擔課題") private String commitment; /** * 我的簡介 */ @Excel(name = "我的簡介") private String personalProfile; /** * 主要著述 */ @Excel(name = "主要著述") private String mainWork; /** * 影音資料 */ @Excel(name = "影音資料") private String videoAudio; /** * 資源類型 */ private Integer resourceType = 22; /** * 附加1 */ private String pro1; /** * 附加2 */ private String pro2; /** * 附加3 */ private String pro3; /************業務字段***************/ private String publics = "公開"; public boolean collectionStatus; // 收藏狀態 @Override public String getDocumentId() { return this.resourceType + "-" + this.getId(); } }
使用:web
/** * 模板下載 */ @GetMapping("/template") @ResponseBody public void template(HttpServletResponse response, String resourceType) throws IOException { ExcelUtil<Scholar> excelUtil = new ExcelUtil<Scholar>(Scholar.class); List<Scholar> list = new ArrayList<Scholar>(); excelUtil.exportExcel(list, "學人模板", response); } /** * 導入 */ @PostMapping("/importExcel") @ResponseBody public void importExcel(HttpServletResponse response, HttpServletRequest request,@RequestParam MultipartFile file) throws IOException { //FileInputStream fileInputStream = new FileInputStream("F://a.xlsx"); InputStream inputStream = file.getInputStream(); ExcelUtil<Scholar> excelUtil = new ExcelUtil<Scholar>(Scholar.class); try { List<Scholar> scholar = excelUtil.importExcel(inputStream); if (!scholar.isEmpty()) { for (Scholar scholar1 :scholar){ int fileId = fileService.insertFile(scholar1.getPhoto()); scholar1.setResourceType(22); scholar1.setPublics("公開"); scholarService.insertScholar(scholar1); } } } catch (Exception e) { e.printStackTrace(); } }
前臺:spring
<!DOCTYPE html> <html lang="zh" xmlns:th="http://www.thymeleaf.org"> <meta charset="utf-8"> <head th:include="include :: header"></head> <body class="white-bg"> <div class="wrapper wrapper-content animated fadeInRight ibox-content"> <form class="form-horizontal m" id="form-excel" method="post" enctype="multipart/form-data"> <input type="hidden" name="importExcelUrl" id="importExcelUrl" th:value="*{importExcelUrl}"> <div class="form-group"> <label class="col-sm-4 control-label ">批量導入數據:</label> <div class="col-sm-8"> <input type="file" id="file" name="file" class="btn btn-success btn-rounded btn-sm"/> </div> </div> <div> <label class="col-sm-4 control-label ">模 板 下 載:</label> <div class="col-sm-8"> <a th:href="*{templateUrl}" class="btn btn-success btn-rounded btn-sm">導入模板</a> </div> </div> </form> </div> <div th:include="include :: footer"></div> <script type="text/javascript"> $("#form-user-resetPwd").validate({ rules: {} }); function submitHandler() { var form = document.getElementById('form-excel'); form .action = $('#importExcelUrl').val(); form.submit(); } </script> </body> </html>
跳轉的路徑:apache
<!DOCTYPE HTML> <html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro"> <meta charset="utf-8"> <head th:include="include :: header"></head> <body class="gray-bg"> <div class="container-div"> <div class="row"> <div class="col-sm-12 search-collapse"> <form id="notice-form"> <div class="select-list"> <ul> <li> 學者姓名:<input type="title" name="title" id="title"/> </li> <li> <a class="btn btn-primary btn-rounded btn-sm" onclick="$.table.search()"><i class="fa fa-search"></i> 搜索</a> <a class="btn btn-warning btn-rounded btn-sm" onclick="$.form.reset()"><i class="fa fa-refresh"></i> 重置</a> <a href="#" class="btn btn-success btn-rounded btn-sm" onclick="$.operate.excel()"><i class="fa fa-plus"></i> 導入</a> </li> </ul> </div> </form> </div> <div class="btn-group-sm hidden-xs" id="toolbar" role="group"> <a class="btn btn-success" onclick="$.operate.add(0)" shiro:hasPermission="module:scholar:add"> <i class="fa fa-plus"></i> 添加 </a> <a class="btn btn-primary btn-edit disabled" onclick="$.operate.edit()" shiro:hasPermission="module:scholar:edit"> <i class="fa fa-edit"></i> 修改 </a> <a class="btn btn-danger btn-del btn-del disabled" onclick="$.operate.removeAll()" shiro:hasPermission="module:scholar:remove"> <i class="fa fa-remove"></i> 刪除 </a> </div> <div class="col-sm-12 select-table table-striped "> <table id="bootstrap-table" data-mobile-responsive="true"></table> </div> </div> </div> <div th:include="include :: footer"></div> <script th:inline="javascript"> var editFlag = [[${@permission.hasPermi('module:scholar:edit')}]]; var removeFlag = [[${@permission.hasPermi('module:scholar:remove')}]]; var prefix = ctx + "module/scholar"; $(function () { var options = { url: prefix + "/list", createUrl: prefix + "/add", updateUrl: prefix + "/edit/{id}", removeUrl: prefix + "/remove", templateUrl: prefix + "/template?resourceType=" + 1, importExcelUrl: prefix + "/importExcel", modalName: "學者(學人)", uniqueId: "id", search: false, columns: [ { checkbox: true }, { title: '序號', align: "center", width: 40, formatter: function (value, row, index) { var table = $('#bootstrap-table'); var pageSize = table.bootstrapTable('getOptions').pageSize; //獲取當前是第幾頁 var pageNumber = table.bootstrapTable('getOptions').pageNumber; //返回序號,注意index是從0開始的,因此要加上1 return pageSize * (pageNumber - 1) + index + 1; } }, /*{ field : 'id', title : '主鍵' },*/ /*{ field : 'createTime', title : '建立時間' }, { field : 'updateTime', title : '更新時間' },*/ { field: 'title', title: '學人姓名', formatter: function (value, row, index) { if(value){ return value.length > 25 ? value.substr(0, 25) + "..." : value; } } }, { field: 'gender', title: '性別', width: '200px' }, { field: 'nationality', title: '國籍', formatter: function (value, row, index) { if(value){ return value.length > 25 ? value.substr(0, 25) + "..." : value; } } }, /*{ field : 'nation', title : '民族' }, { field : 'birth', title : '出生年月' }, { field : 'university', title : '畢業院校' },*/ { field: 'jobAddress', title: '工做單位', formatter: function (value, row, index) { if(value){ return value.length > 25 ? value.substr(0, 25) + "..." : value; } } }, /* { field : 'photo', title : '照片' }, { field : 'resume', title : '簡歷' }, { field : 'positionStatus', title : '任職狀況' }, { field : 'position', title : '職稱' }, { field : 'researchField', title : '研究領域' }, { field : 'commitment', title : '承擔課題' }, { field : 'personalProfile', title : '我的簡介' }, { field : 'mainWork', title : '主要著述' }, { field : 'videoAudio', title : '影音資料' },*/ /*{ field : 'resourceType', title : '資源類型' },*/ { field: 'pro1', title: '首字母' },/* { field : 'pro2', title : '附加2' }, { field : 'pro3', title : '附加3' },*/ { title: '操做', align: 'center', formatter: function (value, row, index) { var actions = []; actions.push('<a class="btn btn-success btn-xs ' + editFlag + '" href="#" onclick="$.operate.edit(\'' + row.id + '\')"><i class="fa fa-edit"></i>修改</a> '); actions.push('<a class="btn btn-danger btn-xs ' + removeFlag + '" href="#" onclick="$.operate.remove(\'' + row.id + '\')"><i class="fa fa-remove"></i>刪除</a>'); return actions.join(''); } }] }; $.table.init(options); }); </script> </body> </html>
js:bootstrap
// excel 導入 excel: function () { var url = ctx + "/common/excel?templateUrl=" + $.table._option.templateUrl + "&importExcelUrl=" + $.table._option.importExcelUrl; $.modal.open($.table._option.modalName + "導入", url, '800', '300'); }