Java 导入导出功能总结

原文链接:https://blog.csdn.net/fanrenxiang/article/details/80985879

项目中经常需要使用导入导出功能来加快数据的操作,尤其是一些项目的后台管理系统,特此奉上我们项目中使用到导入导出代码,均可以实际使用。准备工作:pom中加入以下依赖:


 
 
  1. <dependency>
  2. <groupId>org.apache.poi</groupId>
  3. <artifactId>poi</artifactId>
  4. <version> 3.15-beta2</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.apache.poi</groupId>
  8. <artifactId>poi-ooxml</artifactId>
  9. <version> 3.15-beta2</version>
  10. </dependency>

导入功能


基本思路:读取到文件--->创建表格并把文件流内容读取到表格中--->解析表格--->持久化


 
 
  1. package com.simons.cn.springbootdemo.util;
  2. import com.simons.cn.springbootdemo.bean.Movie;
  3. import com.simons.cn.springbootdemo.service.Weixin.IndexService;
  4. import org.apache.poi.ss.usermodel.*;
  5. import org.slf4j.Logger;
  6. import org.slf4j.LoggerFactory;
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.stereotype.Service;
  9. import org.springframework.util.FileCopyUtils;
  10. import org.springframework.web.multipart.MultipartFile;
  11. import java.io.File;
  12. import java.io.FileInputStream;
  13. import java.util.ArrayList;
  14. import java.util.List;
  15. @Service
  16. public class FilePortUtil {
  17. private static final Logger log = LoggerFactory.getLogger(FilePortUtil.class);
  18. @Autowired
  19. private IndexService indexService;
  20. /**
  21. * 导入功能
  22. *
  23. * @param multipartFile
  24. * @return
  25. */
  26. public int fileImport(MultipartFile multipartFile) {
  27. File file = null;
  28. Workbook workbook = null;
  29. int totalNum = 0;
  30. /*得到的path是 /D:/springbootdemo/target/springbootdemo/WEB-INF/classes/ */
  31. String path = FilePortUtil.class.getClassLoader().getResource( "/").getPath();
  32. /*拼接后的path就是 /D:/springbootdemo/target/springbootdemo/WEB-INF/电影正式资源.xlsx /*/
  33. path = path.substring( 0, path.indexOf( "WEB-INF") + "WEB-INF".length()) + "/" + multipartFile.getOriginalFilename();
  34. file = new File(path);
  35. try {
  36. /*把文件流copy读取到文件中*/
  37. FileCopyUtils.copy(multipartFile.getBytes(), file);
  38. workbook = WorkbookFactory.create( new FileInputStream(file));
  39. List<Movie> list = new ArrayList<>();
  40. /*遍历sheet页*/
  41. for ( int i = 0; i < workbook.getNumberOfSheets(); i++) {
  42. Sheet sheet = workbook.getSheetAt(i);
  43. if (sheet == null) {
  44. continue;
  45. }
  46. /*统计导入的总条数,要是你的excell包含了表头,就不用加1了*/
  47. if (sheet.getLastRowNum() > 0) {
  48. totalNum += sheet.getLastRowNum() + 1;
  49. }
  50. /*遍历行,这里j的初始值取1是因为我的表格里第一行是表头*/
  51. for ( int j = 1; j < sheet.getPhysicalNumberOfRows(); j++) {
  52. Row row = sheet.getRow(j);
  53. /*解析列,下标从0开始*/
  54. Cell cell2 = row.getCell( 2);
  55. Cell cell3 = row.getCell( 3);
  56. if (cell2 == null || cell3 == null) {
  57. continue;
  58. }
  59. String name = this.getCellValue(cell2);
  60. String original = this.getCellValue(cell3);
  61. /*我这里省略了很多数据清洗、校验的代码*/
  62. Movie movie = new Movie();
  63. movie.setName(name);
  64. movie.setOriginal(original);
  65. list.add(movie);
  66. }
  67. /*持久化:批量新增*/
  68. indexService.insertBatch(list);
  69. }
  70. /*解析完删除此路径下的文件*/
  71. file.delete();
  72. return totalNum;
  73. } catch (Exception e) {
  74. e.printStackTrace();
  75. log.error( "导入功能公用类异常exception={}", e);
  76. }
  77. return totalNum;
  78. }
  79. public String getCellValue(Cell cell) {
  80. if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
  81. return String.valueOf(cell.getBooleanCellValue());
  82. } else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
  83. Double d = cell.getNumericCellValue();
  84. return String.valueOf(d.intValue());
  85. }
  86. return String.valueOf(cell.getStringCellValue());
  87. }
  88. }

一般来说,每个导入功能处理的逻辑不太一样,里面的校验、数据对象也不太一样,所以我这里就没有封装成公用类而仅仅写成service,里面具体的逻辑交由程序员填充。


导出功能

导出功能是最常用的,下面的代码中用到了反射的思想,比如,你查询出来的List<T>结果集,只想导出指定的那些字段数据,就非常方便了,代码如下:


基本思路:创建表格对象--->将数据set进表格--->将表格流写入response返回


 
 
  1. package com.simons.cn.springbootdemo.util;
  2. import org.apache.commons.collections.CollectionUtils;
  3. import org.apache.commons.lang.time.DateFormatUtils;
  4. import org.apache.poi.hssf.usermodel.*;
  5. import org.slf4j.Logger;
  6. import org.slf4j.LoggerFactory;
  7. import org.springframework.stereotype.Service;
  8. import javax.servlet.http.HttpServletResponse;
  9. import java.beans.PropertyDescriptor;
  10. import java.lang.reflect.Field;
  11. import java.lang.reflect.Method;
  12. import java.util.Date;
  13. import java.util.Iterator;
  14. import java.util.List;
  15. public class FilePortUtil {
  16. private static final Logger log = LoggerFactory.getLogger(FilePortUtil.class);
  17. /**
  18. * 导出功能
  19. * 注意:泛型T类字段名和containBean集合里字段名字的一致性
  20. *
  21. * @param response
  22. * @param title 表名
  23. * @param headers 表头
  24. * @param list 数据集
  25. * @param containBean 数据集类型字段
  26. * @param <T>
  27. * @throws Exception
  28. */
  29. public static <T> void exportExcel(HttpServletResponse response, String title, String[] headers, List<T> list, List<String> containBean) throws Exception {
  30. HSSFWorkbook workbook = null;
  31. try {
  32. workbook = new HSSFWorkbook();
  33. HSSFSheet sheet = workbook.createSheet(title);
  34. HSSFRow row = sheet.createRow( 0);
  35. /*创建第一行表头*/
  36. for ( short i = 0; i < headers.length; i++) {
  37. HSSFCell cell = row.createCell(i);
  38. HSSFRichTextString text = new HSSFRichTextString(headers[i]);
  39. cell.setCellValue(text);
  40. }
  41. Iterator<T> it = list.iterator();
  42. int index = 0;
  43. while (it.hasNext()) {
  44. index++;
  45. row = sheet.createRow(index);
  46. T t = (T) it.next();
  47. /*反射得到字段*/
  48. Field[] fields = t.getClass().getDeclaredFields();
  49. /*如果需要匹配*/
  50. if (CollectionUtils.isNotEmpty(containBean)) {
  51. for ( int j = 0; j < containBean.size(); j++) {
  52. for ( int i = 0; i < fields.length; i++) {
  53. Field field = fields[i];
  54. if (!field.getName().equals(containBean.get(j)))
  55. continue;
  56. /*给每一列set值*/
  57. setCellValue(t, field, row, j);
  58. }
  59. }
  60. } else {
  61. for ( int i = 0; i < fields.length; i++) {
  62. Field field = fields[i];
  63. setCellValue(t, field, row, i);
  64. }
  65. }
  66. }
  67. /*application/vnd.ms-excel告诉浏览器要下载的是个excel*/
  68. response.setContentType( "application/vnd.ms-excel;charset=UTF-8");
  69. /*请求头设置,Content-Disposition为下载标识,attachment标识以附件方式下载*/
  70. response.addHeader( "Content-Disposition", "attachment;filename=" + new String((title).getBytes(), "ISO8859-1") + ".xls");
  71. workbook.write(response.getOutputStream());
  72. } finally {
  73. if (workbook != null) {
  74. workbook.close();
  75. }
  76. }
  77. }
  78. /**
  79. * 设置每一行中的列
  80. *
  81. * @param t
  82. * @param field
  83. * @param row
  84. * @param index
  85. * @param <T>
  86. */
  87. private static <T> void setCellValue(T t, Field field, HSSFRow row, int index) {
  88. HSSFCell cell = row.createCell(index);
  89. Object value = invoke(t, field);
  90. String textValue = null;
  91. if (value != null) {
  92. if (value instanceof Date) {
  93. Date date = (Date) value;
  94. textValue = DateFormatUtils.format(date, "yyyy-MM-dd HH:mm:ss");
  95. } else {
  96. textValue = value.toString();
  97. }
  98. }
  99. if (textValue != null) {
  100. cell.setCellValue(textValue);
  101. }
  102. }
  103. /**
  104. * 反射映射数据集字段
  105. *
  106. * @param t
  107. * @param field
  108. * @param <T>
  109. * @return
  110. */
  111. private static <T> Object invoke(T t, Field field) {
  112. try {
  113. String fieldName = field.getName();
  114. PropertyDescriptor pd = new PropertyDescriptor(fieldName, t.getClass());
  115. Method method = pd.getReadMethod();
  116. return method.invoke(t);
  117. } catch (Exception e) {
  118. return null;
  119. }
  120. }
  121. }


 
 
  1. @ResponseBody
  2. @RequestMapping(value = "/fileport", method = RequestMethod.GET)
  3. public void filePort(HttpServletResponse response) {
  4. //导出的表名
  5. String title = "测试导出活动参与记录";
  6. //表中第一行表头字段
  7. String[] headers = { "主键id", "用户名", "活动id", "奖品id", "中奖时间"};
  8. //实际数据结果集
  9. List<UserReward> listObject = userRewardDao.queryUserActivityInfo( "2018shuangdan_act", "2018shuangdan_evt", "sdthanks");
  10. //具体需要写入excel需要哪些字段,这些字段取自UserReward类,也就是上面的实际数据结果集的泛型
  11. List<String> listColumn = Arrays.asList( "id", "username", "actId", "rewardId", "winRewardTime");
  12. try {
  13. FilePortUtil.exportExcel(response, title, headers, listObject, listColumn);
  14. } catch (Exception e) {
  15. e.printStackTrace();
  16. }
  17. }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值