浏览代码

新增excel 导入功能

wuweihao 4 年之前
父节点
当前提交
7dde849b2d

+ 6 - 0
gis_common/pom.xml

@@ -171,6 +171,12 @@
             <artifactId>httpclient</artifactId>
         </dependency>
 
+        <!--excel 依赖工具包, hutool需要用的-->
+        <dependency>
+            <groupId>org.apache.poi</groupId>
+            <artifactId>poi-ooxml</artifactId>
+        </dependency>
+
 
 
     </dependencies>

+ 88 - 0
gis_common/src/main/java/com/gis/common/util/ExcelUtils.java

@@ -0,0 +1,88 @@
+package com.gis.common.util;
+
+import cn.hutool.poi.excel.ExcelUtil;
+import cn.hutool.poi.excel.ExcelWriter;
+import cn.hutool.poi.excel.sax.handler.RowHandler;
+import lombok.extern.slf4j.Slf4j;
+import org.junit.Test;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Created by owen on 2021/3/8 0008 15:50
+ */
+@Slf4j
+public class ExcelUtils {
+
+    private static List<List<Object>> lineList = new ArrayList<>();
+
+    /**
+     *
+     * @param rows 每行数据
+     * @param savePath 保存地址 xxx.xlsx
+     * @param rowTitle 标题
+     */
+    public static void createExcel(List rows, String savePath, Map<String, String> rowTitle) {
+        log.info("rows size: {}", rows.size());
+//        log.info("savePath: {}", savePath);
+        ExcelWriter writer = ExcelUtil.getWriter(savePath);
+
+        //自定义标题别名
+        if (rowTitle != null) {
+            for (Map.Entry<String, String> a : rowTitle.entrySet()) {
+                writer.addHeaderAlias(a.getKey(), a.getValue());
+            }
+        }
+
+        // 一次性写出内容,使用默认样式,强制输出标题
+        writer.write(rows, true);
+        // 关闭writer,释放内存
+        writer.close();
+        log.info("excel完成:" +  savePath);
+
+    }
+
+
+    @Test
+    public void test(){
+        readExcel("F:\\test\\excel\\1.xlsx", 0);
+    }
+
+    public static void readExcel(String excelPath, Integer sheetIndex) {
+
+
+        // reader方法的第二个参数是sheet的序号,-1表示读取所有sheet,0表示第一个sheet,依此类推
+        ExcelUtil.read07BySax(excelPath, sheetIndex, createRowHandler());
+        //去除excel中的第一行数据
+        lineList.remove(0);
+
+
+        for (List<Object> objects : lineList) {
+            System.out.println(objects);
+        }
+
+
+
+
+
+    }
+
+    private static RowHandler createRowHandler() {
+
+        //清空一下集合中的数据
+        lineList.removeAll(lineList);
+        return new RowHandler() {
+            @Override
+            public void handle(int sheetIndex, int rowIndex, List<Object> rowlist) {
+//                log.info("[{}] [{}] {}", sheetIndex, rowIndex, rowlist);
+                lineList.add(rowlist);
+            }
+
+        };
+    }
+
+
+
+}

+ 12 - 6
gis_common/src/main/java/com/gis/common/util/Result.java

@@ -6,6 +6,7 @@ import lombok.Data;
 import lombok.NoArgsConstructor;
 
 import java.io.Serializable;
+import java.time.LocalDateTime;
 
 /**
  * 通用返回类
@@ -21,6 +22,7 @@ public class Result<T> implements Serializable {
     public static int CODE_SUCCESS = 0;
     public static int CODE_FAILURE = -1;
     public static String[] NOOP = new String[]{};
+    public static LocalDateTime dateTime = LocalDateTime.now();
 
     /**
      * 处理状态:0: 成功, 1: 失败
@@ -37,6 +39,10 @@ public class Result<T> implements Serializable {
      */
     @ApiModelProperty(value = "返回数据", name = "data")
     private T data;
+
+
+    @ApiModelProperty(value = "返回时间", name = "timestamp")
+    private LocalDateTime timestamp;
     /**
      * 处理成功,并返回数据
      *
@@ -44,7 +50,7 @@ public class Result<T> implements Serializable {
      * @return data
      */
     public static Result success(Object data) {
-        return new Result(CODE_SUCCESS, SUCCESS_MSG, data);
+        return new Result(CODE_SUCCESS, SUCCESS_MSG, data, dateTime);
     }
     /**
      * 处理成功
@@ -52,7 +58,7 @@ public class Result<T> implements Serializable {
      * @return data
      */
     public static Result success() {
-        return new Result(CODE_SUCCESS, SUCCESS_MSG, NOOP);
+        return new Result(CODE_SUCCESS, SUCCESS_MSG, NOOP, dateTime);
     }
     /**
      * 处理成功
@@ -61,7 +67,7 @@ public class Result<T> implements Serializable {
      * @return data
      */
     public static Result success(String msg) {
-        return new Result(CODE_SUCCESS, msg, NOOP);
+        return new Result(CODE_SUCCESS, msg, NOOP, dateTime);
     }
     /**
      * 处理成功
@@ -71,7 +77,7 @@ public class Result<T> implements Serializable {
      * @return data
      */
     public static Result success(String msg, Object data) {
-        return new Result(CODE_SUCCESS, msg, data);
+        return new Result(CODE_SUCCESS, msg, data, dateTime);
     }
     /**
      * 处理失败,并返回数据(一般为错误信息)
@@ -81,7 +87,7 @@ public class Result<T> implements Serializable {
      * @return data
      */
     public static Result failure(int code, String msg) {
-        return new Result(code, msg, NOOP);
+        return new Result(code, msg, NOOP, dateTime);
     }
     /**
      * 处理失败
@@ -96,6 +102,6 @@ public class Result<T> implements Serializable {
     @Override
     public String toString() {
         return "JsonResult [code=" + code + ", msg=" + msg + ", data="
-                + data + "]";
+                + data +", timestamp="+ timestamp + "]";
     }
 }

+ 8 - 0
gis_mapper/src/main/java/com/gis/mapper/QuestionMapper.java

@@ -2,7 +2,9 @@ package com.gis.mapper;
 
 
 import com.gis.domain.po.QuestionEntity;
+import org.apache.ibatis.annotations.Delete;
 import org.apache.ibatis.annotations.Mapper;
+import org.apache.ibatis.annotations.Param;
 import org.apache.ibatis.annotations.Select;
 import org.springframework.stereotype.Component;
 
@@ -17,4 +19,10 @@ public interface QuestionMapper extends IBaseMapper<QuestionEntity, Long> {
 
     @Select("select id from tb_question where is_delete = 0 AND topic_type = #{type} ORDER BY RAND() LIMIT #{pcs} ")
     List<Integer> getRandomIds(Integer type, Integer pcs);
+
+    @Delete("truncate table tb_question")
+    void truncateTableQuestion();
+
+    @Delete("truncate table tb_answer")
+    void truncateTableAnswaer();
 }

+ 3 - 0
gis_service/src/main/java/com/gis/service/QuestionService.java

@@ -3,6 +3,7 @@ package com.gis.service;
 
 import com.gis.common.util.Result;
 import com.gis.domain.po.QuestionEntity;
+import org.springframework.web.multipart.MultipartFile;
 
 import java.util.List;
 
@@ -13,4 +14,6 @@ public interface QuestionService extends IBaseService<QuestionEntity, Long> {
 
 
     Result<List<QuestionEntity>> getQuestion(Integer type, Integer pcs);
+
+    Result uploadExcel(MultipartFile file);
 }

+ 117 - 0
gis_service/src/main/java/com/gis/service/impl/QuestionServiceImpl.java

@@ -1,5 +1,10 @@
 package com.gis.service.impl;
 
+import cn.hutool.core.date.DateUtil;
+import cn.hutool.core.io.FileUtil;
+import cn.hutool.poi.excel.ExcelUtil;
+import cn.hutool.poi.excel.sax.handler.RowHandler;
+import com.gis.common.exception.BaseRuntimeException;
 import com.gis.common.util.Result;
 import com.gis.domain.po.AnswerEntity;
 import com.gis.domain.po.QuestionEntity;
@@ -12,8 +17,10 @@ import lombok.extern.slf4j.Slf4j;
 import org.apache.commons.lang3.StringUtils;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
+import org.springframework.web.multipart.MultipartFile;
 
 import java.util.ArrayList;
+import java.util.Date;
 import java.util.List;
 
 
@@ -34,6 +41,10 @@ public class QuestionServiceImpl extends IBaseServiceImpl<QuestionEntity, Long>
     @Autowired
     AnswerMapper answerMapper;
 
+
+    private static List<List<Object>> qusetionlineList = new ArrayList<>();
+    private static List<List<Object>> answerlineList = new ArrayList<>();
+
     @Override
     public IBaseMapper<QuestionEntity, Long> getBaseMapper() {
         return this.entityMapper;
@@ -112,4 +123,110 @@ public class QuestionServiceImpl extends IBaseServiceImpl<QuestionEntity, Long>
 
 
     }
+
+    @Override
+    public Result uploadExcel(MultipartFile file) {
+        if (file == null) {
+            return Result.failure("文件为空");
+        }
+        String originalFilename = file.getOriginalFilename();
+        if (!originalFilename.endsWith(".xlsx")) {
+            return Result.failure("只支持.slsx格式的Excel");
+        }
+        String suffix = StringUtils.substringAfterLast(originalFilename, ".");
+
+        String time = DateUtil.format(new Date(), "yyyyMMdd_HHmmssSSS");
+        // 目录位置
+        String savePath = configConstant.serverBasePath + time + "."+ suffix;
+        log.info("savePath: " + savePath);
+        try {
+            FileUtil.writeFromStream(file.getInputStream(), savePath);
+            if (!FileUtil.exist(savePath)) {
+                log.error("excel文件不存在: {}", savePath);
+                return Result.failure("excel文件不存在");
+            }
+
+            updateQuestion(savePath, 0);
+            log.info("更新问题完成");
+            updateAnswer(savePath, 1);
+            log.info("更新答案完成");
+            return Result.success();
+        } catch (Exception e) {
+//            e.printStackTrace();
+            log.error(e.getMessage());
+            throw new BaseRuntimeException("文件内容有误,请联系管理员");
+        }
+    }
+
+    private void updateQuestion(String excelPath, Integer sheetIndex){
+        // reader方法的第二个参数是sheet的序号,-1表示读取所有sheet,0表示第一个sheet,依此类推
+        ExcelUtil.read07BySax(excelPath, sheetIndex, createRowHandler());
+        //去除excel中的第一行数据
+        qusetionlineList.remove(0);
+        // 清空问题表
+        entityMapper.truncateTableQuestion();
+        for (List<Object> row : qusetionlineList) {
+            QuestionEntity questionEntity = new QuestionEntity();
+            questionEntity.setId((Long)row.get(0) );
+            questionEntity.setTitle((String) row.get(1));
+            questionEntity.setType((String)row.get(2));
+            questionEntity.setTopicType(Integer.parseInt(row.get(3).toString()));
+
+            log.info("entity: {}", questionEntity.toString());
+            this.save(questionEntity);
+
+        }
+
+    }
+
+
+
+    private static RowHandler createRowHandler() {
+        qusetionlineList.removeAll(qusetionlineList);
+        return new RowHandler() {
+            @Override
+            public void handle(int sheetIndex, int rowIndex, List rowlist) {
+//                log.info("[{}] [{}] {}", sheetIndex, rowIndex, rowlist);
+                qusetionlineList.add(rowlist);
+
+
+            }
+
+        };
+    }
+
+    private void updateAnswer(String excelPath, Integer sheetIndex){
+        // reader方法的第二个参数是sheet的序号,-1表示读取所有sheet,0表示第一个sheet,依此类推
+        ExcelUtil.read07BySax(excelPath, sheetIndex, answerRowHandler());
+        //去除excel中的第一行数据
+        answerlineList.remove(0);
+        // 清空表
+        entityMapper.truncateTableAnswaer();
+        for (List<Object> row : answerlineList) {
+            AnswerEntity entity = new AnswerEntity();
+            entity.setContent((String) row.get(0));
+            entity.setCorrect(Integer.parseInt(row.get(1).toString()));
+            entity.setSort(Integer.parseInt(row.get(2).toString()));
+            entity.setQuestionId((Long)row.get(3));
+            log.info("entity: {}", entity.toString());
+            answerService.save(entity);
+        }
+
+    }
+
+    private static RowHandler answerRowHandler() {
+        answerlineList.removeAll(answerlineList);
+        return new RowHandler() {
+            @Override
+            public void handle(int sheetIndex, int rowIndex, List rowlist) {
+                // rowlist: 具体没一行的数据
+                answerlineList.add(rowlist);
+            }
+
+        };
+    }
+
+
+
+
 }

+ 10 - 4
gis_web/src/main/java/com/gis/web/controller/WebController.java

@@ -8,10 +8,8 @@ import io.swagger.annotations.Api;
 import io.swagger.annotations.ApiOperation;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.web.bind.annotation.GetMapping;
-import org.springframework.web.bind.annotation.PathVariable;
-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 java.util.List;
 
@@ -43,6 +41,14 @@ public class WebController extends BaseController {
 
 
 
+    @ApiOperation(value = "更新问题、答案", notes = "上传excel.xlsx文件, 必须有两个sheet, sheet1:问题, sheet2:答案 ")
+    @PostMapping("uploadExcel")
+    public Result uploadExcel(MultipartFile file) {
+
+        return questionService.uploadExcel(file);
+    }
+
+
 
 
 

+ 10 - 0
pom.xml

@@ -49,6 +49,7 @@
         <tk.mybatis.version>2.0.2</tk.mybatis.version>
         <tk.mapper.version>4.0.3</tk.mapper.version>
         <pagehelper.version>1.2.5</pagehelper.version>
+        <poi.version>4.1.2</poi.version>
 
     </properties>
 
@@ -245,6 +246,15 @@
                 <version>${httpclient.version}</version>
             </dependency>
 
+
+
+            <!--excel 依赖工具包, hutool需要用的-->
+            <dependency>
+                <groupId>org.apache.poi</groupId>
+                <artifactId>poi-ooxml</artifactId>
+                <version>${poi.version}</version>
+            </dependency>
+
         </dependencies>
     </dependencyManagement>