游戏开发论坛

 找回密码
 立即注册
搜索
查看: 2738|回复: 0

从零开始实现放置游戏(六):Excel批量导入

[复制链接]

1万

主题

1万

帖子

3万

积分

论坛元老

Rank: 8Rank: 8

积分
36572
发表于 2019-11-12 13:33:06 | 显示全部楼层 |阅读模式
前面我们已经实现了在后台管理系统中,对配置数据的增删查改。但每次添加只能添加一条数据,实际生产中,大量数据通过手工一条一条添加不太现实。本章我们就实现通过Excel导入配置数据的功能。这里我们还是以地图数据为例,其他配置项可参照此例。

涉及的功能点主要有对office文档的编程、文件上传功能。流程图大致如下:

1.png

一、添加依赖项

解析office文档推荐使用免费的开源组件POI,已经可以满足80%的功能需求。上传文件需要依赖commons-fileupload包。我们在pom中添加下列代码:

  1. <!-- office组件 -->
  2. <dependency>
  3.     <groupId>org.apache.poi</groupId>
  4.     <artifactId>poi</artifactId>
  5.     <version>4.1.0</version>
  6. </dependency>
  7. <dependency>
  8.     <groupId>org.apache.poi</groupId>
  9.     <artifactId>poi-ooxml</artifactId>
  10.     <version>4.1.0</version>
  11. </dependency>
  12. <!-- 文件上传 -->
  13. <dependency>
  14.     <groupId>commons-fileupload</groupId>
  15.     <artifactId>commons-fileupload</artifactId>
  16.     <version>1.4</version>
  17. </dependency>
复制代码

另外,之前我们配置的mvc视图解析器只能解析简单的视图,上传文件需要支持multipart。在spring-mvc.xml中添加如下配置:

  1. <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
  2.     <property name="defaultEncoding" value="UTF-8"></property>
  3.     <property name="maxUploadSize" value="10485770"></property>
  4.     <property name="maxInMemorySize" value="10485760"></property>
  5. </bean>
复制代码

这里配置了上传最大限制10MB,对于excel上传来说足矣。


二、文件上传、解析、落库

在MapController中,我们添加3个方法

MapController.java

  1. @ResponseBody
  2.     @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
  3.     public Object importExcel(HttpServletRequest request) {
  4.         try {
  5.             ServletContext servletContext = request.getServletContext();
  6.             String uploadPath = servletContext.getRealPath("/upload");
  7.             File dir = new File(uploadPath);
  8.             if (!dir.exists()) {
  9.                 dir.mkdir();
  10.             }

  11.             CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(servletContext);
  12.             if (multipartResolver.isMultipart(request)) {
  13.                 MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
  14.                 Iterator<String> iter = multiRequest.getFileNames();
  15.                 while (iter.hasNext()) {
  16.                     MultipartFile file = multiRequest.getFile(iter.next());
  17.                     if (file.getSize() > 0) {
  18.                         String fileName = file.getOriginalFilename();
  19.                         String extension = fileName.substring(fileName.lastIndexOf("."));
  20.                         if (!extension.toLowerCase().equals(".xls") && !extension.toLowerCase().equals(".xlsx")) {
  21.                             throw new Exception("不支持的文档格式!请上传.xls或.xlsx格式的文档!");
  22.                         }

  23.                         String destFileName = fileName + "_" + System.currentTimeMillis() + extension;
  24.                         File destFile = new File(uploadPath, destFileName);
  25.                         file.transferTo(destFile);
  26.                         List<WowMap> dataList = this.loadExcelData(destFile.getPath());
  27.                         this.saveExcelData(dataList);
  28.                         if (!destFile.delete()) {
  29.                             logger.warn("临时文件删除失败:" + destFile.getAbsolutePath());
  30.                         }
  31.                     }
  32.                 }
  33.             }

  34.             return CommonResult.success();
  35.         } catch (Exception ex) {
  36.             logger.error(ex.getMessage(), ex);
  37.             return CommonResult.fail();
  38.         }
  39.     }

  40.     protected List<WowMap> loadExcelData(String excelPath) throws Exception {
  41.         FileInputStream fileInputStream = new FileInputStream(excelPath);
  42.         XSSFWorkbook workbook = new XSSFWorkbook(fileInputStream);
  43.         Sheet sheet = workbook.getSheet("地图");
  44.         List<WowMap> wowMapList = new ArrayList<>();
  45.         // 处理当前页,循环读取每一行
  46.         String createUser = this.currentUserName();
  47.         for (int rowNum = 2; rowNum <= sheet.getLastRowNum(); rowNum++) {
  48.             XSSFRow row = (XSSFRow) sheet.getRow(rowNum);
  49.             String name = PoiUtil.getCellValue(row.getCell(2));
  50.             DataDict.Occupy occupy = DataDict.Occupy.getByDesc(PoiUtil.getCellValue(row.getCell(4)));
  51.             WowMap wowMap = new WowMap();
  52.             wowMap.setName(name);
  53.             wowMap.setOccupy(occupy.getCode());
  54.             wowMap.setDescription("");
  55.             wowMap.setCreateUser(createUser);
  56.             wowMapList.add(wowMap);
  57.         }

  58.         fileInputStream.close();
  59.         return wowMapList;
  60.     }

  61.     protected void saveExcelData(List<WowMap> dataList) {
  62.         wowMapManager.batchInsert(dataList);
  63.     }
复制代码

其中,importExcel方法,时候对应前端点击导入按钮时的后端入口,在这个方法中,我们定义了临时文件上传路径,校验了文件名后缀,保存上传的文件到服务器,并在操作结束后将临时文件删除; loadExcelData方法,利用POI组件读取解析Excel数据,Excel数据怎么配我们可以自由定义,这里读取时自由调整对应的行列即可,本例使用的Excel在文末给出的源码中可以找到; saveExcelData方法,将解析到的数据列表存入数据库,这里调用的batchInsert批量添加方法,在前面讲增删查改的时候已经提前实现了。

另外,在使用POI组件读取Excel数据时,需要先判断单元格格式,我们创建一个工具类PoiUtil来实现此功能,这种在以后的其他项目中也可以使用的工具类,我们把它提取出来,放到util模块中,作为我们的通用工具包,以便日后使用。在util模块新建包com.idlewow.util.poi,并添加PoiUtil类:

PoiUtil.java

  1. package com.idlewow.util.poi;

  2. import org.apache.commons.lang3.StringUtils;
  3. import org.apache.poi.ss.usermodel.Cell;
  4. import org.apache.poi.ss.usermodel.CellType;
  5. import org.apache.poi.ss.usermodel.DateUtil;

  6. import java.text.DecimalFormat;
  7. import java.text.SimpleDateFormat;
  8. import java.util.Date;

  9. public class PoiUtil {
  10.     public static String getCellValue(Cell cell) {
  11.         CellType cellType = cell.getCellType();
  12.         if (cellType.equals(CellType.STRING)) {
  13.             return cell.getStringCellValue();
  14.         } else if (cellType.equals(CellType.NUMERIC)) {
  15.             if (DateUtil.isCellDateFormatted(cell)) {
  16.                 Date date = cell.getDateCellValue();
  17.                 return date == null ? "" : new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
  18.             } else {
  19.                 return new DecimalFormat("0.##").format(cell.getNumericCellValue());
  20.             }
  21.         } else if (cellType.equals(CellType.FORMULA)) {
  22.             if (StringUtils.isNotBlank(cell.getStringCellValue())) {
  23.                 return cell.getStringCellValue();
  24.             } else {
  25.                 return cell.getNumericCellValue() + "";
  26.             }
  27.         } else if (cellType.equals(CellType.BOOLEAN)) {
  28.             return cell.getBooleanCellValue() ? "TRUE" : "FALSE";
  29.         } else {
  30.             return "";
  31.         }
  32.     }
  33. }
复制代码

工具类提取到util模块后,需要在util模块也添加对Poi的依赖,并在rms模块添加对util的依赖。这里util模块中,依赖项的scope为provided即可,仅在编译阶段使用,因为在引用此工具包的模块中肯定已经引入了POI依赖,无需重复打包:

  1. <dependencies>
  2.     <dependency>
  3.         <groupId>org.apache.poi</groupId>
  4.         <artifactId>poi</artifactId>
  5.         <version>4.1.0</version>
  6.         <scope>provided</scope>
  7.     </dependency>
  8.     <dependency>
  9.         <groupId>org.apache.poi</groupId>
  10.         <artifactId>poi-ooxml</artifactId>
  11.         <version>4.1.0</version>
  12.         <scope>provided</scope>
  13.     </dependency>
  14. </dependencies>
复制代码

三、修改前端页面

在地图列表页面list.jsp中,添加导入excel的按钮。

  1. <form>
  2.     …………
  3.     …………
  4.     <div class="layui-inline layui-show-xs-block">
  5.         <button type="button" class="layui-btn" onclick="xadmin.open('添加地图','add',500,500)">
  6.             <i class="layui-icon"></i>添加地图
  7.         </button>
  8.     </div>
  9.     <div class="layui-upload layui-inline layui-show-xs-block">
  10.         <button type="button" class="layui-btn layui-btn-normal" id="btnSelectFile">选择Excel</button>
  11.         <button type="button" class="layui-btn" id="btnImport">开始导入</button>
  12.     </div>
  13. </form>
复制代码

在列表页面的list.js中,绑定相应的按钮事件。

  1. layui.use(['upload', 'table', 'form'], function () {
  2.     …………
  3.     …………

  4.     layui.upload.render({
  5.         elem: '#btnSelectFile',
  6.         url: '/manage/map/importExcel',
  7.         accept: 'file',
  8.         exts: 'xls|xlsx',
  9.         auto: false,
  10.         bindAction: '#btnImport',
  11.         done: function (result) {
  12.             if (result.code === 1) {
  13.                 layer.alert(result.message, {icon: 6},
  14.                     function () {
  15.                         layui.layer.closeAll();
  16.                         layui.table.reload('datatable');
  17.                     });
  18.             } else {
  19.                 layer.alert(result.message, {icon: 5});
  20.             }
  21.         }
  22.     });
  23. });
复制代码


四、运行效果

以上,excel导入的功能就全部完成了,我们运行下看下效果:

2.gif

小结

本章通过导入Excel文件,实现了批量录入的功能。

源码下载地址:https://idlestudio.ctfile.com/fs/14960372-383760599

本文原文地址:https://www.cnblogs.com/lyosaki88/p/idlewow_6.html

相关阅读:
从零开始实现放置游戏(一):准备工作
从零开始实现放置游戏(二):整体框架搭建
从零开始实现放置游戏(三):后台管理系统搭建
从零开始实现放置游戏(四)后台数值配置的增删查改
从零开始实现放置游戏(五):管理系统搭建之实现切面日志

作者:丶谦信
博客地址:https://www.cnblogs.com/lyosaki88/p/idlewow_6.html


您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

作品发布|文章投稿|广告合作|关于本站|游戏开发论坛 ( 闽ICP备17032699号-3 )

GMT+8, 2024-4-24 20:05

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表