浏览代码

章节模板 - 模板下载、批量导入
问卷模板 - 模板下载、批量导入

wangggziwen 8 月之前
父节点
当前提交
1ab4372cc3

+ 73 - 4
rc-admin/src/main/java/com/ruoyi/web/controller/common/CommonController.java

@@ -1,17 +1,19 @@
 package com.ruoyi.web.controller.common;
 
+import java.io.BufferedInputStream;
+import java.io.BufferedOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
 import java.util.ArrayList;
 import java.util.List;
+import javax.servlet.ServletOutputStream;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.http.MediaType;
-import org.springframework.web.bind.annotation.GetMapping;
-import org.springframework.web.bind.annotation.PostMapping;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.bind.annotation.*;
 import org.springframework.web.multipart.MultipartFile;
 import com.ruoyi.common.config.RuoYiConfig;
 import com.ruoyi.common.constant.Constants;
@@ -160,4 +162,71 @@ public class CommonController
             log.error("下载文件失败", e);
         }
     }
+
+    /**
+     * 导入下载模板
+     */
+    @RequestMapping("/template")
+    @ResponseBody
+    public void template(String type, HttpServletRequest request, HttpServletResponse response) throws IOException {
+        String downloadname = "";
+        String url = "";
+        switch (type) {
+            case "questionnairetemplate":
+                downloadname = "审计问卷导入模板.xlsx";
+                url = "static/template/questionnairetemplate.xlsx";
+                break;
+            case "chaptertemplate":
+                downloadname = "审计章节导入模板.xlsx";
+                url = "static/template/chaptertemplate.xlsx";
+                break;
+        }
+        InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(url);
+
+        downloadFile(downloadname, is, request, response);
+    }
+
+    public static void downloadFile(String filename, InputStream is, HttpServletRequest request, HttpServletResponse response) throws IOException {
+        response.reset();
+        if (filename.endsWith(".doc") || filename.endsWith(".docx")) {
+            response.setContentType("application/msword;charset=utf-8");
+        } else if (filename.endsWith(".xls") || filename.endsWith(".xlsx")) {
+            response.setContentType("application/vnd.ms-excel;charset=utf-8");
+        } else {
+            response.setHeader("content-type", "application/octet-stream");
+        }
+        //下载文件的名称
+        response.setHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes("UTF-8"), "iso-8859-1"));
+        request.setCharacterEncoding("UTF-8");
+
+        ServletOutputStream out = null;
+        BufferedInputStream bis = null;
+        BufferedOutputStream bos = null;
+        try {
+            out = response.getOutputStream();
+            bis = new BufferedInputStream(is);
+            bos = new BufferedOutputStream(out);
+            byte[] buff = new byte[2048];
+            int bytesRead;
+            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
+                bos.write(buff, 0, bytesRead);
+            }
+        } catch (IOException e) {
+            e.printStackTrace();
+        } finally {
+            try {
+                if (bis != null) {
+                    bis.close();
+                }
+                if (bos != null) {
+                    bos.close();
+                }
+                if (is != null) {
+                    is.close();
+                }
+            } catch (IOException e) {
+                e.printStackTrace();
+            }
+        }
+    }
 }

+ 87 - 8
rc-admin/src/main/java/com/ruoyi/web/controller/rc/TChapterTemplateController.java

@@ -1,19 +1,29 @@
 package com.ruoyi.web.controller.rc;
 
+import com.alibaba.fastjson2.JSON;
 import com.ruoyi.common.core.domain.entity.SysDept;
+import com.ruoyi.common.core.domain.entity.SysDictData;
+import com.ruoyi.common.core.domain.entity.SysUser;
+import com.ruoyi.common.utils.DateUtils;
+import com.ruoyi.common.utils.file.ExcelUtils;
 import com.ruoyi.system.service.ISysDeptService;
+
+import java.io.IOException;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
 import java.util.List;
 import javax.servlet.http.HttpServletResponse;
+
+import com.ruoyi.system.service.ISysDictTypeService;
+import com.ruoyi.system.service.ISysPostService;
+import org.apache.commons.collections4.CollectionUtils;
+import org.apache.poi.ss.usermodel.Cell;
+import org.apache.poi.ss.usermodel.Row;
+import org.apache.poi.ss.usermodel.Sheet;
+import org.apache.poi.ss.usermodel.Workbook;
 import org.springframework.security.access.prepost.PreAuthorize;
 import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.web.bind.annotation.GetMapping;
-import org.springframework.web.bind.annotation.PostMapping;
-import org.springframework.web.bind.annotation.PutMapping;
-import org.springframework.web.bind.annotation.DeleteMapping;
-import org.springframework.web.bind.annotation.PathVariable;
-import org.springframework.web.bind.annotation.RequestBody;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.bind.annotation.*;
 import com.ruoyi.common.annotation.Log;
 import com.ruoyi.common.core.controller.BaseController;
 import com.ruoyi.common.core.domain.AjaxResult;
@@ -23,6 +33,7 @@ import com.ruoyi.rc.service.ITChapterTemplateService;
 import com.ruoyi.common.utils.poi.ExcelUtil;
 import com.ruoyi.common.core.page.TableDataInfo;
 import com.ruoyi.common.utils.StringUtils;
+import org.springframework.web.multipart.MultipartFile;
 
 /**
  * 章节模板Controller
@@ -40,6 +51,9 @@ public class TChapterTemplateController extends BaseController
     @Autowired
     private ISysDeptService deptService;
 
+    @Autowired
+    private ISysDictTypeService sysDictTypeService;
+
     /**
      * 查询全部章节模板列表
      */
@@ -120,4 +134,69 @@ public class TChapterTemplateController extends BaseController
     {
         return toAjax(tChapterTemplateService.deleteTChapterTemplateByIds(ids));
     }
+
+    @PostMapping("/importData")
+    public AjaxResult importData(@RequestParam("file") MultipartFile file) throws IOException {
+        //报错行数统计
+        List<Integer> failRow = new ArrayList<>();
+        Workbook workbook = ExcelUtils.getWorkBook(file);
+        Sheet sheet = workbook.getSheetAt(0);
+        List<TChapterTemplate> list = new ArrayList<>();
+        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
+        int rowNum = sheet.getPhysicalNumberOfRows();
+        int failNumber = 0;
+        for (int i = 1; i < rowNum; i++) {
+            try {
+                logger.info("读取行数:" + i);
+                Row row = sheet.getRow(i);
+                int cellNum = row.getLastCellNum();
+                TChapterTemplate entity = new TChapterTemplate();
+                for (int j = 0; j < cellNum; j++) {
+                    Cell cell = row.getCell(j);
+                    if (cell == null) {
+                        continue;
+                    }
+                    String cellValue = ExcelUtils.getCellValue(cell);
+                    logger.info("cellValue:" + cellValue);
+                    if (j == 0) {
+                        entity.setCode(cellValue);
+                    } else if (j == 1) {
+                        entity.setName(cellValue);
+                    }
+                }
+                logger.info("entity:" + entity);
+                list.add(entity);
+            } catch (Exception e) {
+                failNumber++;
+                logger.info("e:" + JSON.toJSONString(e));
+                failRow.add(i + 1);
+            }
+        }
+        int successNumber = 0;
+        int failNum = 0;
+        for (TChapterTemplate t : list) {
+            failNum++;
+            try {
+                TChapterTemplate obj = new TChapterTemplate();
+                obj.setCode(t.getCode());
+                if (CollectionUtils.isEmpty(tChapterTemplateService.selectTChapterTemplateList(obj))) {
+                    add(t);
+                    successNumber++;
+                } else {
+                    failNumber++;
+                    logger.info("======================数据已存在");
+                    failRow.add(failNum + 1);
+                }
+            } catch (Exception e) {
+                failNumber++;
+                logger.info("e:" + e);
+                failRow.add(failNum + 1);
+            }
+        }
+        logger.info("list:" + JSON.toJSONString(list));
+        logger.info("successNumber:" + successNumber);
+        logger.info("failNumber:" + failNumber);
+        logger.info("failRow:" + failRow);
+        return AjaxResult.success(String.valueOf(successNumber), failRow);
+    }
 }

+ 98 - 8
rc-admin/src/main/java/com/ruoyi/web/controller/rc/TQuestionnaireTemplateController.java

@@ -1,19 +1,28 @@
 package com.ruoyi.web.controller.rc;
 
+import com.alibaba.fastjson2.JSON;
 import com.ruoyi.common.core.domain.entity.SysDept;
+import com.ruoyi.common.core.domain.entity.SysDictData;
+import com.ruoyi.common.utils.file.ExcelUtils;
+import com.ruoyi.rc.domain.TChapterTemplate;
+import com.ruoyi.rc.domain.TQuestionnaire;
 import com.ruoyi.system.service.ISysDeptService;
+
+import java.io.IOException;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
 import java.util.List;
 import javax.servlet.http.HttpServletResponse;
+
+import com.ruoyi.system.service.ISysDictTypeService;
+import org.apache.commons.collections4.CollectionUtils;
+import org.apache.poi.ss.usermodel.Cell;
+import org.apache.poi.ss.usermodel.Row;
+import org.apache.poi.ss.usermodel.Sheet;
+import org.apache.poi.ss.usermodel.Workbook;
 import org.springframework.security.access.prepost.PreAuthorize;
 import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.web.bind.annotation.GetMapping;
-import org.springframework.web.bind.annotation.PostMapping;
-import org.springframework.web.bind.annotation.PutMapping;
-import org.springframework.web.bind.annotation.DeleteMapping;
-import org.springframework.web.bind.annotation.PathVariable;
-import org.springframework.web.bind.annotation.RequestBody;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.bind.annotation.*;
 import com.ruoyi.common.annotation.Log;
 import com.ruoyi.common.core.controller.BaseController;
 import com.ruoyi.common.core.domain.AjaxResult;
@@ -23,6 +32,7 @@ import com.ruoyi.rc.service.ITQuestionnaireTemplateService;
 import com.ruoyi.common.utils.poi.ExcelUtil;
 import com.ruoyi.common.core.page.TableDataInfo;
 import com.ruoyi.common.utils.StringUtils;
+import org.springframework.web.multipart.MultipartFile;
 
 /**
  * 问卷模板Controller
@@ -40,6 +50,9 @@ public class TQuestionnaireTemplateController extends BaseController
     @Autowired
     private ISysDeptService deptService;
 
+    @Autowired
+    private ISysDictTypeService sysDictTypeService;
+
     /**
      * 查询问卷模板列表
      */
@@ -126,4 +139,81 @@ public class TQuestionnaireTemplateController extends BaseController
     {
         return toAjax(tQuestionnaireTemplateService.deleteTQuestionnaireTemplateByIds(ids));
     }
+
+    @PostMapping("/importData")
+    public AjaxResult importData(@RequestParam("file") MultipartFile file) throws IOException {
+        List<SysDictData> typeDict = sysDictTypeService.selectDictDataByType("t_sec_sub_chap_type");
+        //报错行数统计
+        List<Integer> failRow = new ArrayList<>();
+        Workbook workbook = ExcelUtils.getWorkBook(file);
+        Sheet sheet = workbook.getSheetAt(0);
+        List<TQuestionnaireTemplate> list = new ArrayList<>();
+        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
+        int rowNum = sheet.getPhysicalNumberOfRows();
+        int failNumber = 0;
+        for (int i = 1; i < rowNum; i++) {
+            try {
+                logger.info("读取行数:" + i);
+                Row row = sheet.getRow(i);
+                int cellNum = row.getLastCellNum();
+                TQuestionnaireTemplate entity = new TQuestionnaireTemplate();
+                for (int j = 0; j < cellNum; j++) {
+                    Cell cell = row.getCell(j);
+                    if (cell == null) {
+                        continue;
+                    }
+                    String cellValue = ExcelUtils.getCellValue(cell);
+                    logger.info("cellValue:" + cellValue);
+                    if (j == 0) {
+                        entity.setChapterCode(cellValue);
+                    } else if (j == 1) {
+                        for (SysDictData data : typeDict) {
+                            if (data.getDictLabel().equals(cellValue)) {
+                                entity.setType(data.getDictValue());
+                            }
+                        }
+                    } else if (j == 2) {
+                        entity.setDirectory(cellValue);
+                    } else if (j == 3) {
+                        entity.setCode(Long.parseLong(cellValue));
+                    } else if (j == 4) {
+                        entity.setName(cellValue);
+                    }
+                }
+                logger.info("entity:" + entity);
+                list.add(entity);
+            } catch (Exception e) {
+                failNumber++;
+                logger.info("e:" + JSON.toJSONString(e));
+                failRow.add(i + 1);
+            }
+        }
+        int successNumber = 0;
+        int failNum = 0;
+        for (TQuestionnaireTemplate t : list) {
+            failNum++;
+            try {
+                TQuestionnaireTemplate obj = new TQuestionnaireTemplate();
+                obj.setDirectory(t.getDirectory());
+                obj.setCode(t.getCode());
+                if (CollectionUtils.isEmpty(tQuestionnaireTemplateService.selectTQuestionnaireTemplateList(obj))) {
+                    add(t);
+                    successNumber++;
+                } else {
+                    failNumber++;
+                    logger.info("======================数据已存在");
+                    failRow.add(failNum + 1);
+                }
+            } catch (Exception e) {
+                failNumber++;
+                logger.info("e:" + e);
+                failRow.add(failNum + 1);
+            }
+        }
+        logger.info("list:" + JSON.toJSONString(list));
+        logger.info("successNumber:" + successNumber);
+        logger.info("failNumber:" + failNumber);
+        logger.info("failRow:" + failRow);
+        return AjaxResult.success(String.valueOf(successNumber), failRow);
+    }
 }

二进制
rc-admin/src/main/resources/static/template/chaptertemplate.xlsx


二进制
rc-admin/src/main/resources/static/template/questionnairetemplate.xlsx


+ 10 - 0
rc-buisness/src/main/java/com/ruoyi/rc/domain/TQuestionnaireTemplate.java

@@ -22,6 +22,8 @@ public class TQuestionnaireTemplate extends BaseEntity
     @Excel(name = "章节id")
     private Long chapterId;
 
+    private String chapterCode;
+
     private String chapterName;
 
     /** 问卷类型 */
@@ -48,6 +50,14 @@ public class TQuestionnaireTemplate extends BaseEntity
     @Excel(name = "装置")
     private String deptName;
 
+    public String getChapterCode() {
+        return chapterCode;
+    }
+
+    public void setChapterCode(String chapterCode) {
+        this.chapterCode = chapterCode;
+    }
+
     public String getChapterName() {
         return chapterName;
     }

+ 11 - 7
rc-buisness/src/main/resources/mapper/rc/TQuestionnaireTemplateMapper.xml

@@ -27,14 +27,14 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
     <select id="selectTQuestionnaireTemplateList" parameterType="TQuestionnaireTemplate" resultMap="TQuestionnaireTemplateResult">
         <include refid="selectTQuestionnaireTemplateVo"/>
         <where>  
-            <if test="chapterId != null "> and chapter_id = #{chapterId}</if>
-            <if test="type != null  and type != ''"> and type = #{type}</if>
-            <if test="directory != null  and directory != ''"> and directory = #{directory}</if>
-            <if test="code != null "> and code = #{code}</if>
-            <if test="name != null  and name != ''"> and name like concat('%', #{name}, '%')</if>
-            <if test="deptId != null  and deptId != ''"> and dept_id = #{deptId}</if>
+            <if test="chapterId != null "> and qt.chapter_id = #{chapterId}</if>
+            <if test="type != null  and type != ''"> and qt.type = #{type}</if>
+            <if test="directory != null  and directory != ''"> and qt.directory = #{directory}</if>
+            <if test="code != null "> and qt.code = #{code}</if>
+            <if test="name != null  and name != ''"> and qt.name like concat('%', #{name}, '%')</if>
+            <if test="deptId != null  and deptId != ''"> and qt.dept_id = #{deptId}</if>
         </where>
-        order by (SUBSTR(qt.directory, 1, INSTR(qt.directory, '.') - 1) + 0) asc, code asc
+        order by (SUBSTR(qt.directory, 1, INSTR(qt.directory, '.') - 1) + 0) asc, qt.code asc
     </select>
     
     <select id="selectTQuestionnaireTemplateById" parameterType="Long" resultMap="TQuestionnaireTemplateResult">
@@ -46,6 +46,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
         insert into t_questionnaire_template
         <trim prefix="(" suffix=")" suffixOverrides=",">
             <if test="chapterId != null">chapter_id,</if>
+            <if test="chapterCode != null">chapter_id,</if>
             <if test="type != null">type,</if>
             <if test="directory != null">directory,</if>
             <if test="code != null">code,</if>
@@ -54,6 +55,9 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
          </trim>
         <trim prefix="values (" suffix=")" suffixOverrides=",">
             <if test="chapterId != null">#{chapterId},</if>
+            <if test="chapterCode != null">
+                (select id from t_chapter_template ct where ct.code = #{chapterCode}),
+            </if>
             <if test="type != null">#{type},</if>
             <if test="directory != null">#{directory},</if>
             <if test="code != null">#{code},</if>

+ 60 - 6
rc-common/src/main/java/com/ruoyi/common/utils/DateUtils.java

@@ -9,11 +9,13 @@ import java.time.LocalTime;
 import java.time.ZoneId;
 import java.time.ZonedDateTime;
 import java.util.Date;
+import java.util.regex.Pattern;
+
 import org.apache.commons.lang3.time.DateFormatUtils;
 
 /**
  * 时间工具类
- * 
+ *
  * @author ruoyi
  */
 public class DateUtils extends org.apache.commons.lang3.time.DateUtils
@@ -29,13 +31,13 @@ public class DateUtils extends org.apache.commons.lang3.time.DateUtils
     public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
 
     private static String[] parsePatterns = {
-            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM", 
+            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
             "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
             "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};
 
     /**
      * 获取当前Date型日期
-     * 
+     *
      * @return Date() 当前日期
      */
     public static Date getNowDate()
@@ -45,7 +47,7 @@ public class DateUtils extends org.apache.commons.lang3.time.DateUtils
 
     /**
      * 获取当前日期, 默认格式为yyyy-MM-dd
-     * 
+     *
      * @return String
      */
     public static String getDate()
@@ -146,8 +148,6 @@ public class DateUtils extends org.apache.commons.lang3.time.DateUtils
 
     /**
      * 计算时间差
-     *
-     * @param endDate 最后时间
      * @param startTime 开始时间
      * @return 时间差(天/小时/分钟)
      */
@@ -188,4 +188,58 @@ public class DateUtils extends org.apache.commons.lang3.time.DateUtils
         ZonedDateTime zdt = localDateTime.atZone(ZoneId.systemDefault());
         return Date.from(zdt.toInstant());
     }
+
+    public static String getDateFormat(String str) {
+        boolean year = false;
+        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
+        if (pattern.matcher(str.substring(0, 4)).matches()) {
+            year = true;
+        }
+        StringBuilder sb = new StringBuilder();
+        int index = 0;
+        if (!year) {
+            if (str.contains("月") || str.contains("-") || str.contains("/") || str.contains(".")) {
+                if (Character.isDigit(str.charAt(0))) {
+                    index = 1;
+                }
+            } else {
+                index = 3;
+            }
+        }
+        for (int i = 0; i < str.length(); i++) {
+            char chr = str.charAt(i);
+            if (Character.isDigit(chr)) {
+                if (index == 0) {
+                    sb.append("y");
+                }
+                if (index == 1) {
+                    sb.append("M");
+                }
+                if (index == 2) {
+                    sb.append("d");
+                }
+                if (index == 3) {
+                    sb.append("H");
+                }
+                if (index == 4) {
+                    sb.append("m");
+                }
+                if (index == 5) {
+                    sb.append("s");
+                }
+                if (index == 6) {
+                    sb.append("S");
+                }
+            } else {
+                if (i > 0) {
+                    char lastChar = str.charAt(i - 1);
+                    if (Character.isDigit(lastChar)) {
+                        index++;
+                    }
+                }
+                sb.append(chr);
+            }
+        }
+        return sb.toString();
+    }
 }

+ 337 - 0
rc-common/src/main/java/com/ruoyi/common/utils/file/ExcelUtils.java

@@ -0,0 +1,337 @@
+package com.ruoyi.common.utils.file;
+
+
+import com.ruoyi.common.config.RuoYiConfig;
+import com.ruoyi.common.constant.Constants;
+import com.ruoyi.common.utils.StringUtils;
+import org.apache.poi.hssf.usermodel.HSSFDataFormat;
+import org.apache.poi.hssf.usermodel.HSSFDateUtil;
+import org.apache.poi.hssf.usermodel.HSSFWorkbook;
+import org.apache.poi.ss.usermodel.*;
+import org.apache.poi.ss.util.CellRangeAddress;
+import org.apache.poi.util.IOUtils;
+import org.apache.poi.xssf.usermodel.XSSFSheet;
+import org.apache.poi.xssf.usermodel.XSSFWorkbook;
+import org.springframework.web.multipart.MultipartFile;
+
+import java.io.*;
+import java.math.BigDecimal;
+import java.text.DecimalFormat;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+
+/**
+ * Created by Administrator on 2018/7/26 0026.
+ */
+public class ExcelUtils {
+
+    public static void insertPicture(XSSFWorkbook workbook, XSSFSheet sheet, String fileUrl, int row, int col, double scaleX, double scaleY) {
+        try {
+            // 输入流
+            String localPath = RuoYiConfig.getProfile();
+            String imagePath = localPath + StringUtils.substringAfter(fileUrl, Constants.RESOURCE_PREFIX);
+            InputStream is = new FileInputStream(imagePath);
+            byte[] bytes = IOUtils.toByteArray(is);
+            @SuppressWarnings("static-access")
+            int pictureIdx = workbook.addPicture(bytes, workbook.PICTURE_TYPE_PNG);
+            CreationHelper helper = workbook.getCreationHelper();
+            Drawing drawing = sheet.createDrawingPatriarch();
+            ClientAnchor anchor = helper.createClientAnchor();
+            // 图片插入坐标
+            anchor.setCol1(col);
+            anchor.setRow1(row);
+            // 插入图片
+            Picture pict = drawing.createPicture(anchor, pictureIdx);
+            pict.resize(scaleX, scaleY);
+            is.close();
+        } catch (FileNotFoundException e) {
+            e.printStackTrace();
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+    }
+
+    public static Workbook getWorkBook(MultipartFile file) {
+        //获得文件名
+        String fileName = file.getOriginalFilename();
+        //创建Workbook工作薄对象,表示整个excel
+        Workbook workbook = null;
+        try {
+            //获取excel文件的io流
+            InputStream is = file.getInputStream();
+            //根据文件后缀名不同(xls和xlsx)获得不同的Workbook实现类对象
+            if (fileName.endsWith("xls")) {
+                //2003
+                workbook = new HSSFWorkbook(is);
+            } else if (fileName.endsWith("xlsx")) {
+                //2007 及2007以上
+                workbook = new XSSFWorkbook(is);
+            }
+        } catch (IOException e) {
+//            log.error(e.getMessage());
+        }
+        return workbook;
+    }
+
+    public static Workbook getWorkBook(File file) {
+        //获得文件名
+        String fileName = file.getName();
+        //创建Workbook工作薄对象,表示整个excel
+        Workbook workbook = null;
+        try {
+            //获取excel文件的io流
+            InputStream is =new FileInputStream(file);
+            //根据文件后缀名不同(xls和xlsx)获得不同的Workbook实现类对象
+            if (fileName.endsWith("xls")) {
+                //2003
+                workbook = new HSSFWorkbook(is);
+            } else if (fileName.endsWith("xlsx")) {
+                //2007 及2007以上
+                workbook = new XSSFWorkbook(is);
+            }
+        } catch (IOException e) {
+//            log.error(e.getMessage());
+        }
+        return workbook;
+    }
+
+    public static String getCellValue(Cell cell) {
+        String cellValue = "";
+        if (cell == null) {
+            return cellValue;
+        }
+        System.out.println("Excel格式:"+ cell.getCellType().name());
+
+        switch (cell.getCellType().name()) {
+            case "STRING":
+                cellValue = cell.getRichStringCellValue().getString();
+                break;
+            case "NUMERIC":
+                System.out.println("Excel数据样式:"+ cell.getCellStyle().getDataFormatString());
+                if("General".equals(cell.getCellStyle().getDataFormatString())){
+                    cellValue = new BigDecimal(cell.getNumericCellValue()).toPlainString();
+                }else if("m/d/yyyy;@".equals(cell.getCellStyle().getDataFormatString())){
+                    cellValue =  new SimpleDateFormat("yyyy-MM-dd").format(cell.getDateCellValue());
+                }else if("@".equals(cell.getCellStyle().getDataFormatString())){
+                    cellValue = cell.getNumericCellValue() + "";
+                }else if(cell.getCellStyle().getDataFormatString().indexOf("0_") > -1){
+                    //数字非日期
+                    System.out.println("Excel值:"+ cell.getNumericCellValue());
+                    cellValue = cell.getNumericCellValue() + "";
+                }else{
+                    try {
+                        cellValue =  new SimpleDateFormat("yyyy-MM-dd").format(cell.getDateCellValue());
+                    }catch (Exception e){
+                        cellValue = cell.getNumericCellValue() + "";
+                    }
+                }
+                break;
+            case "BLANK":
+                cellValue = "";
+                break;
+            default:
+                cellValue = cell.toString();
+                break;
+        }
+        //判断数据的类型
+//        switch (cell.getCellType()) {
+//            case Cell.CELL_TYPE_NUMERIC: //数字
+//                cellValue = stringDateProcess(cell);
+//                break;
+//            case Cell.CELL_TYPE_STRING: //字符串
+//                cellValue = String.valueOf(cell.getStringCellValue());
+//                break;
+//            case Cell.CELL_TYPE_BOOLEAN: //Boolean
+//                cellValue = String.valueOf(cell.getBooleanCellValue());
+//                break;
+//            case Cell.CELL_TYPE_FORMULA: //公式
+//                cellValue = String.valueOf(cell.getCellFormula());
+//                break;
+//            case Cell.CELL_TYPE_BLANK: //空值
+//                cellValue = "";
+//                break;
+//            case Cell.CELL_TYPE_ERROR: //故障
+//                cellValue = "非法字符";
+//                break;
+//            default:
+//                cellValue = "未知类型";
+//                break;
+//        }
+//        cellValue = String.valueOf(cell.getStringCellValue());
+        return cellValue;
+    }
+
+    /**
+     * 时间格式处理
+     *
+     * @return
+     * @author Liu Xin Nan
+     * @data 2017年11月27日
+     */
+    public static String stringDateProcess(Cell cell) {
+        String result = new String();
+        if (HSSFDateUtil.isCellDateFormatted(cell)) {// 处理日期格式、时间格式
+            SimpleDateFormat sdf = null;
+            if (cell.getCellStyle().getDataFormat() == HSSFDataFormat.getBuiltinFormat("h:mm")) {
+                sdf = new SimpleDateFormat("HH:mm");
+            } else {// 日期
+                sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
+            }
+            Date date = cell.getDateCellValue();
+            result = sdf.format(date);
+        } else if (cell.getCellStyle().getDataFormat() == 58) {
+            // 处理自定义日期格式:m月d日(通过判断单元格的格式id解决,id的值是58)
+            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
+            double value = cell.getNumericCellValue();
+            Date date = DateUtil
+                    .getJavaDate(value);
+            result = sdf.format(date);
+        } else {
+            double value = cell.getNumericCellValue();
+            CellStyle style = cell.getCellStyle();
+            DecimalFormat format = new DecimalFormat();
+            String temp = style.getDataFormatString();
+            // 单元格设置成常规
+            if (temp.equals("General")) {
+                format.applyPattern("#");
+            }
+            result = format.format(value);
+        }
+
+        return result;
+    }
+
+    /**
+     * 合并单元格处理,获取合并行
+     *
+     * @param sheet
+     * @return List<CellRangeAddress>
+     */
+    public static List<CellRangeAddress> getCombineCell(Sheet sheet) {
+        List<CellRangeAddress> list = new ArrayList<CellRangeAddress>();
+        //获得一个 sheet 中合并单元格的数量
+        int sheetmergerCount = sheet.getNumMergedRegions();
+        //遍历所有的合并单元格
+        for (int i = 0; i < sheetmergerCount; i++) {
+            //获得合并单元格保存进list中
+            CellRangeAddress ca = sheet.getMergedRegion(i);
+            list.add(ca);
+        }
+        return list;
+    }
+
+    public static int getRowNum(List<CellRangeAddress> listCombineCell, Cell cell, Sheet sheet) {
+        int xr = 0;
+        int firstC = 0;
+        int lastC = 0;
+        int firstR = 0;
+        int lastR = 0;
+        for (CellRangeAddress ca : listCombineCell) {
+            //获得合并单元格的起始行, 结束行, 起始列, 结束列
+            firstC = ca.getFirstColumn();
+            lastC = ca.getLastColumn();
+            firstR = ca.getFirstRow();
+            lastR = ca.getLastRow();
+            if (cell.getRowIndex() >= firstR && cell.getRowIndex() <= lastR) {
+                if (cell.getColumnIndex() >= firstC && cell.getColumnIndex() <= lastC) {
+                    xr = lastR;
+                }
+            }
+        }
+        return xr;
+
+    }
+
+    /**
+     * 判断单元格是否为合并单元格,是的话则将单元格的值返回
+     *
+     * @param listCombineCell 存放合并单元格的list
+     * @param cell            需要判断的单元格
+     * @param sheet           sheet
+     * @return
+     */
+    public static String isCombineCell(List<CellRangeAddress> listCombineCell, Cell cell, Sheet sheet)
+            throws Exception {
+        int firstC = 0;
+        int lastC = 0;
+        int firstR = 0;
+        int lastR = 0;
+        String cellValue = null;
+        for (CellRangeAddress ca : listCombineCell) {
+            //获得合并单元格的起始行, 结束行, 起始列, 结束列
+            firstC = ca.getFirstColumn();
+            lastC = ca.getLastColumn();
+            firstR = ca.getFirstRow();
+            lastR = ca.getLastRow();
+            if (cell.getRowIndex() >= firstR && cell.getRowIndex() <= lastR) {
+                if (cell.getColumnIndex() >= firstC && cell.getColumnIndex() <= lastC) {
+                    Row fRow = sheet.getRow(firstR);
+                    Cell fCell = fRow.getCell(firstC);
+                    cellValue = getCellValue(fCell);
+                    break;
+                }
+            } else {
+                cellValue = "";
+            }
+        }
+        return cellValue;
+    }
+
+    /**
+     * 获取合并单元格的值
+     *
+     * @param sheet
+     * @param row
+     * @param column
+     * @return
+     */
+    public static String getMergedRegionValue(Sheet sheet, int row, int column) {
+        int sheetMergeCount = sheet.getNumMergedRegions();
+
+        for (int i = 0; i < sheetMergeCount; i++) {
+            CellRangeAddress ca = sheet.getMergedRegion(i);
+            int firstColumn = ca.getFirstColumn();
+            int lastColumn = ca.getLastColumn();
+            int firstRow = ca.getFirstRow();
+            int lastRow = ca.getLastRow();
+
+            if (row >= firstRow && row <= lastRow) {
+                if (column >= firstColumn && column <= lastColumn) {
+                    Row fRow = sheet.getRow(firstRow);
+                    Cell fCell = fRow.getCell(firstColumn);
+                    return getCellValue(fCell);
+                }
+            }
+        }
+
+        return null;
+    }
+
+    /**
+     * 判断指定的单元格是否是合并单元格
+     *
+     * @param sheet
+     * @param row    行下标
+     * @param column 列下标
+     * @return
+     */
+    public static boolean isMergedRegion(Sheet sheet, int row, int column) {
+        int sheetMergeCount = sheet.getNumMergedRegions();
+        for (int i = 0; i < sheetMergeCount; i++) {
+            CellRangeAddress range = sheet.getMergedRegion(i);
+            int firstColumn = range.getFirstColumn();
+            int lastColumn = range.getLastColumn();
+            int firstRow = range.getFirstRow();
+            int lastRow = range.getLastRow();
+            if (row >= firstRow && row <= lastRow) {
+                if (column >= firstColumn && column <= lastColumn) {
+                    return true;
+                }
+            }
+        }
+        return false;
+    }
+
+}

+ 1 - 1
rc-framework/src/main/java/com/ruoyi/framework/config/SecurityConfig.java

@@ -115,7 +115,7 @@ public class SecurityConfig
                     // 静态资源,可匿名访问
                     .antMatchers(HttpMethod.GET, "/", "/*.html", "/**/*.html", "/**/*.css", "/**/*.js", "/profile/**").permitAll()
                     .antMatchers("/swagger-ui.html", "/swagger-resources/**", "/webjars/**", "/*/api-docs", "/druid/**").permitAll()
-                        .antMatchers("/ehs/approvedanger/processImg/**").permitAll()
+                        .antMatchers("/ehs/approvedanger/processImg/**", "/common/template").permitAll()
                     // 除上面外的所有请求全部需要鉴权认证
                     .anyRequest().authenticated();
             })

+ 92 - 0
ruoyi-ui/src/views/rc/chaptertemplate/index.vue

@@ -56,6 +56,16 @@
           v-hasPermi="['rc:chaptertemplate:remove']"
         >删除</el-button>
       </el-col>
+      <el-col :span="1.5">
+        <el-button
+          type="info"
+          plain
+          icon="el-icon-upload2"
+          size="mini"
+          @click="handleImport"
+          v-hasPermi="['rc:chaptertemplate:edit']"
+        >导入</el-button>
+      </el-col>
       <el-col :span="1.5">
         <el-button
           type="warning"
@@ -116,17 +126,70 @@
         <el-button @click="cancel">取 消</el-button>
       </div>
     </el-dialog>
+
+    <!-- 用户导入对话框 -->
+    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
+      <el-upload
+        ref="upload"
+        :limit="1"
+        accept=".xlsx, .xls"
+        :headers="upload.headers"
+        :action="upload.url + '?updateSupport=' + upload.updateSupport"
+        :disabled="upload.isUploading"
+        :on-progress="handleFileUploadProgress"
+        :on-success="handleFileSuccess"
+        :auto-upload="false"
+        drag
+      >
+        <i class="el-icon-upload"></i>
+        <div class="el-upload__text">
+          将文件拖到此处,或
+          <em>点击上传</em>
+        </div>
+        <div class="el-upload__tip" slot="tip">
+          <!--          <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据-->
+          <el-link type="info" style="font-size:12px" @click="importTemplate">下载模板</el-link>
+        </div>
+        <form ref="downloadFileForm" :action="upload.downloadAction" target="FORMSUBMIT">
+          <input name="type" :value="upload.type" hidden/>
+        </form>
+        <div class="el-upload__tip" style="color:red" slot="tip">提示:仅允许导入“xls”或“xlsx”格式文件!</div>
+      </el-upload>
+      <div slot="footer" class="dialog-footer">
+        <el-button type="primary" @click="submitFileForm">确 定</el-button>
+        <el-button @click="upload.open = false">取 消</el-button>
+      </div>
+    </el-dialog>
   </div>
 </template>
 
 <script>
 import { listChaptertemplate, getChaptertemplate, delChaptertemplate, addChaptertemplate, updateChaptertemplate } from "@/api/rc/chaptertemplate";
 import { listDept } from "@/api/system/dept";
+import { getToken } from "@/utils/auth";
 
 export default {
   name: "Chaptertemplate",
   data() {
     return {
+      // 用户导入参数
+      upload: {
+        downloadAction: process.env.VUE_APP_BASE_API + '/common/template',
+        //下载模板类型
+        type: "chaptertemplate",
+        // 是否显示弹出层(用户导入)
+        open: false,
+        // 弹出层标题(用户导入)
+        title: "",
+        // 是否禁用上传
+        isUploading: false,
+        // 是否更新已经存在的用户数据
+        updateSupport: 0,
+        // 设置上传的请求头部
+        headers: { Authorization: "Bearer " + getToken() },
+        // 上传的地址
+        url: process.env.VUE_APP_BASE_API + "/rc/chaptertemplate/importData"
+      },
       // 遮罩层
       loading: true,
       // 选中数组
@@ -281,6 +344,35 @@ export default {
       this.download('rc/chaptertemplate/export', {
         ...this.queryParams
       }, `chaptertemplate_${new Date().getTime()}.xlsx`)
+    },
+    /** 下载模板操作 */
+    importTemplate() {
+      this.$refs['downloadFileForm'].submit()
+    },
+    // 文件上传成功处理
+    handleFileSuccess(response, file, fileList) {
+      this.upload.open = false;
+      this.upload.isUploading = false;
+      this.$refs.upload.clearFiles();
+      if (response.data[0] != null) {
+        this.$alert('成功导入' + response.msg + '条数据' + "," + '第' + response.data + '行数据出现错误导入失败' + "。", '导入结果', {dangerouslyUseHTMLString: true});
+      } else {
+        this.$alert('成功导入' + response.msg + '条数据', '导入结果', {dangerouslyUseHTMLString: true});
+      }
+      this.getList();
+    },
+    // 提交上传文件
+    submitFileForm() {
+      this.$refs.upload.submit();
+    },
+    /** 导入按钮操作 */
+    handleImport() {
+      this.upload.title = "导入";
+      this.upload.open = true;
+    },
+    // 文件上传中处理
+    handleFileUploadProgress(event, file, fileList) {
+      this.upload.isUploading = true;
     }
   }
 };

+ 94 - 1
ruoyi-ui/src/views/rc/questionnairetemplate/index.vue

@@ -84,6 +84,16 @@
           v-hasPermi="['rc:questionnairetemplate:remove']"
         >删除</el-button>
       </el-col>
+      <el-col :span="1.5">
+        <el-button
+          type="info"
+          plain
+          icon="el-icon-upload2"
+          size="mini"
+          @click="handleImport"
+          v-hasPermi="['rc:questionnairetemplate:edit']"
+        >导入</el-button>
+      </el-col>
       <el-col :span="1.5">
         <el-button
           type="warning"
@@ -174,6 +184,41 @@
         <el-button @click="cancel">取 消</el-button>
       </div>
     </el-dialog>
+
+
+    <!-- 用户导入对话框 -->
+    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
+      <el-upload
+        ref="upload"
+        :limit="1"
+        accept=".xlsx, .xls"
+        :headers="upload.headers"
+        :action="upload.url + '?updateSupport=' + upload.updateSupport"
+        :disabled="upload.isUploading"
+        :on-progress="handleFileUploadProgress"
+        :on-success="handleFileSuccess"
+        :auto-upload="false"
+        drag
+      >
+        <i class="el-icon-upload"></i>
+        <div class="el-upload__text">
+          将文件拖到此处,或
+          <em>点击上传</em>
+        </div>
+        <div class="el-upload__tip" slot="tip">
+          <!--          <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据-->
+          <el-link type="info" style="font-size:12px" @click="importTemplate">下载模板</el-link>
+        </div>
+        <form ref="downloadFileForm" :action="upload.downloadAction" target="FORMSUBMIT">
+          <input name="type" :value="upload.type" hidden/>
+        </form>
+        <div class="el-upload__tip" style="color:red" slot="tip">提示:仅允许导入“xls”或“xlsx”格式文件!</div>
+      </el-upload>
+      <div slot="footer" class="dialog-footer">
+        <el-button type="primary" @click="submitFileForm">确 定</el-button>
+        <el-button @click="upload.open = false">取 消</el-button>
+      </div>
+    </el-dialog>
   </div>
 </template>
 
@@ -181,12 +226,31 @@
 import { listQuestionnairetemplate, getQuestionnairetemplate, delQuestionnairetemplate, addQuestionnairetemplate, updateQuestionnairetemplate } from "@/api/rc/questionnairetemplate";
 import { listDept } from "@/api/system/dept";
 import { listAllChaptertemplate } from "@/api/rc/chaptertemplate";
+import { getToken } from "@/utils/auth";
 
 export default {
   name: "Questionnairetemplate",
   dicts: ['t_sec_sub_chap_type'],
   data() {
     return {
+      // 用户导入参数
+      upload: {
+        downloadAction: process.env.VUE_APP_BASE_API + '/common/template',
+        //下载模板类型
+        type: "questionnairetemplate",
+        // 是否显示弹出层(用户导入)
+        open: false,
+        // 弹出层标题(用户导入)
+        title: "",
+        // 是否禁用上传
+        isUploading: false,
+        // 是否更新已经存在的用户数据
+        updateSupport: 0,
+        // 设置上传的请求头部
+        headers: { Authorization: "Bearer " + getToken() },
+        // 上传的地址
+        url: process.env.VUE_APP_BASE_API + "/rc/questionnairetemplate/importData"
+      },
       // 遮罩层
       loading: true,
       // 选中数组
@@ -360,7 +424,36 @@ export default {
       this.download('rc/questionnairetemplate/export', {
         ...this.queryParams
       }, `questionnairetemplate_${new Date().getTime()}.xlsx`)
-    }
+    },
+    /** 下载模板操作 */
+    importTemplate() {
+      this.$refs['downloadFileForm'].submit()
+    },
+    // 文件上传成功处理
+    handleFileSuccess(response, file, fileList) {
+      this.upload.open = false;
+      this.upload.isUploading = false;
+      this.$refs.upload.clearFiles();
+      if (response.data[0] != null) {
+        this.$alert('成功导入' + response.msg + '条数据' + "," + '第' + response.data + '行数据出现错误导入失败' + "。", '导入结果', {dangerouslyUseHTMLString: true});
+      } else {
+        this.$alert('成功导入' + response.msg + '条数据', '导入结果', {dangerouslyUseHTMLString: true});
+      }
+      this.getList();
+    },
+    // 提交上传文件
+    submitFileForm() {
+      this.$refs.upload.submit();
+    },
+    /** 导入按钮操作 */
+    handleImport() {
+      this.upload.title = "导入";
+      this.upload.open = true;
+    },
+    // 文件上传中处理
+    handleFileUploadProgress(event, file, fileList) {
+      this.upload.isUploading = true;
+    },
   }
 };
 </script>