Spring Boot实战之导出excel

来源:互联网 发布:程序员基础知识 编辑:程序博客网 时间:2024/06/03 17:46

Spring Boot实战之导出excel

本文使用Apache POI实现excel文档的导出。 实现从数据库读取数据——生成excel——上传到AzureStorage的流程

数据库操作,及文件上传AzureStorage的流程可以参考之前的文章

http://blog.csdn.net/sun_t89/article/details/51912905

http://blog.csdn.net/sun_t89/article/details/51956392


Apache POI详细操作,可以参考

http://www.cnblogs.com/LiZhiW/p/4313789.html?utm_source=tuicool&utm_medium=referral


1、修改pom.xml,添加Apache POI库

[html] view plain copy
  1. <dependency>  
  2.             <groupId>org.apache.poi</groupId>  
  3.             <artifactId>poi</artifactId>  
  4.             <version>3.14</version>  
  5.         </dependency>  

2、添加导出数据表的数据模型

[java] view plain copy
  1. package com.xiaofangtech.sunt.bean;  
  2.   
  3. import java.math.BigDecimal;  
  4. import java.util.Date;  
  5.   
  6. import javax.persistence.Entity;  
  7. import javax.persistence.GeneratedValue;  
  8. import javax.persistence.GenerationType;  
  9. import javax.persistence.Id;  
  10. import javax.persistence.Table;  
  11.   
  12. @Entity  
  13. @Table(name="t_statistics")  
  14. public class StatisticsInfo {  
  15.     @Id  
  16.     @GeneratedValue(strategy = GenerationType.AUTO)  
  17.     private long id;  
  18.     private BigDecimal money;  
  19.     private String description;  
  20.     private Date currentdate;  
  21.     public long getId() {  
  22.         return id;  
  23.     }  
  24.     public void setId(long id) {  
  25.         this.id = id;  
  26.     }  
  27.     public BigDecimal getMoney() {  
  28.         return money;  
  29.     }  
  30.     public void setMoney(BigDecimal money) {  
  31.         this.money = money;  
  32.     }  
  33.     public String getDescription() {  
  34.         return description;  
  35.     }  
  36.     public void setDescription(String description) {  
  37.         this.description = description;  
  38.     }  
  39.     public Date getCurrentdate() {  
  40.         return currentdate;  
  41.     }  
  42.     public void setCurrentdate(Date currentdate) {  
  43.         this.currentdate = currentdate;  
  44.     }  
  45. }  


3、添加数据访问接口类StatisticsRepository,本文查询所有数据,不另外添加方法,直接使用findAll方法

[java] view plain copy
  1. package com.xiaofangtech.sunt.repository;  
  2.   
  3. import org.springframework.data.repository.CrudRepository;  
  4.   
  5. import com.xiaofangtech.sunt.bean.StatisticsInfo;  
  6.   
  7. public interface StatisticsRepository extends CrudRepository<StatisticsInfo, Long>{  
  8.   
  9. }  
4、创建ExcelController,读取数据库,生成excel文件,并上传到AzureStorage

[java] view plain copy
  1. package com.xiaofangtech.sunt.controller;  
  2.   
  3. import java.io.ByteArrayInputStream;  
  4. import java.io.ByteArrayOutputStream;  
  5. import java.io.IOException;  
  6. import java.text.SimpleDateFormat;  
  7. import java.util.Date;  
  8. import java.util.HashMap;  
  9. import java.util.List;  
  10. import java.util.Map;  
  11. import java.util.UUID;  
  12.   
  13. import org.apache.poi.hssf.usermodel.HSSFCell;  
  14. import org.apache.poi.hssf.usermodel.HSSFCellStyle;  
  15. import org.apache.poi.hssf.usermodel.HSSFDataFormat;  
  16. import org.apache.poi.hssf.usermodel.HSSFFont;  
  17. import org.apache.poi.hssf.usermodel.HSSFRow;  
  18. import org.apache.poi.hssf.usermodel.HSSFSheet;  
  19. import org.apache.poi.hssf.usermodel.HSSFWorkbook;  
  20. import org.springframework.beans.factory.annotation.Autowired;  
  21. import org.springframework.web.bind.annotation.RequestMapping;  
  22. import org.springframework.web.bind.annotation.RestController;  
  23.   
  24. import com.microsoft.azure.storage.blob.CloudBlobContainer;  
  25. import com.microsoft.azure.storage.blob.CloudBlockBlob;  
  26. import com.xiaofangtech.sunt.bean.StatisticsInfo;  
  27. import com.xiaofangtech.sunt.repository.StatisticsRepository;  
  28. import com.xiaofangtech.sunt.storage.BlobHelper;  
  29. import com.xiaofangtech.sunt.storage.StorageConfig;  
  30. import com.xiaofangtech.sunt.utils.ResultMsg;  
  31. import com.xiaofangtech.sunt.utils.ResultStatusCode;  
  32.   
  33.   
  34. @RestController  
  35. @RequestMapping("excel")  
  36. public class ExcelController {  
  37.       
  38.     @Autowired  
  39.     private StatisticsRepository statisticsRepository;  
  40.       
  41.     @Autowired  
  42.     private StorageConfig storageConfig;  
  43.       
  44.     /*** 
  45.      * 创建表头 
  46.      * @param workbook 
  47.      * @param sheet 
  48.      */  
  49.     private void createTitle(HSSFWorkbook workbook, HSSFSheet sheet)  
  50.     {  
  51.         HSSFRow row = sheet.createRow(0);  
  52.         //设置列宽,setColumnWidth的第二个参数要乘以256,这个参数的单位是1/256个字符宽度  
  53.         sheet.setColumnWidth(212*256);  
  54.         sheet.setColumnWidth(317*256);  
  55.           
  56.         //设置为居中加粗  
  57.         HSSFCellStyle style = workbook.createCellStyle();  
  58.         HSSFFont font = workbook.createFont();  
  59.         font.setBold(true);  
  60.         style.setAlignment(HSSFCellStyle.ALIGN_CENTER);  
  61.         style.setFont(font);  
  62.           
  63.         HSSFCell cell;  
  64.         cell = row.createCell(0);  
  65.         cell.setCellValue("序号");  
  66.         cell.setCellStyle(style);  
  67.           
  68.         cell = row.createCell(1);  
  69.         cell.setCellValue("金额");  
  70.         cell.setCellStyle(style);  
  71.           
  72.         cell = row.createCell(2);  
  73.         cell.setCellValue("描述");  
  74.         cell.setCellStyle(style);  
  75.           
  76.         cell = row.createCell(3);  
  77.         cell.setCellValue("日期");  
  78.         cell.setCellStyle(style);  
  79.     }  
  80.       
  81.     /*** 
  82.      * 获取excel数据 
  83.      * @return 返回文件名称及excel文件的URL 
  84.      * @throws IOException 
  85.      */  
  86.     @SuppressWarnings({ "unchecked""rawtypes" })  
  87.     @RequestMapping("getExcel")  
  88.     public Object getExcel() throws IOException  
  89.     {  
  90.         HSSFWorkbook workbook = new HSSFWorkbook();  
  91.         HSSFSheet sheet = workbook.createSheet("统计表");  
  92.         createTitle(workbook, sheet);  
  93.         List<StatisticsInfo> entities = (List<StatisticsInfo>) statisticsRepository.findAll();  
  94.           
  95.         //设置日期格式  
  96.         HSSFCellStyle style=workbook.createCellStyle();  
  97.         style.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm"));  
  98.           
  99.         //新增数据行,并且设置单元格数据  
  100.         int rowNum = 1;  
  101.         for (StatisticsInfo statisticsInfo:entities) {  
  102.               
  103.             HSSFRow row = sheet.createRow(rowNum);  
  104.             row.createCell(0).setCellValue(statisticsInfo.getId());  
  105.             row.createCell(1).setCellValue(statisticsInfo.getMoney().toString());  
  106.             row.createCell(2).setCellValue(statisticsInfo.getDescription());  
  107.             HSSFCell cell = row.createCell(3);  
  108.             cell.setCellValue(statisticsInfo.getCurrentdate());  
  109.             cell.setCellStyle(style);  
  110.             rowNum++;  
  111.         }  
  112.           
  113.         //拼装blobName  
  114.         String fileName = "测试数据统计表.xlsx";  
  115.         SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");  
  116.         String dateTime = dateFormat.format(new Date());  
  117.         String blobName =  dateTime + "/" + UUID.randomUUID().toString().replaceAll("-""") + "/" + fileName;  
  118.           
  119.         //获取或创建container  
  120.         CloudBlobContainer blobContainer = BlobHelper.getBlobContainer("temp", storageConfig);  
  121.         //设置文件类型,并且上传到azure blob  
  122.         try {  
  123.             CloudBlockBlob blob = blobContainer.getBlockBlobReference(blobName);  
  124.             ByteArrayOutputStream out = new ByteArrayOutputStream();  
  125.             workbook.write(out);  
  126.             ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());  
  127.               
  128.             blob.upload(in, out.toByteArray().length);  
  129.             Map map = new HashMap();  
  130.             map.put("fileName", fileName);  
  131.             map.put("excelUrl", blob.getUri().toString());  
  132.               
  133.             ResultMsg resultMsg = new ResultMsg(ResultStatusCode.OK.getErrcode(),  
  134.                     ResultStatusCode.OK.getErrmsg(), map);  
  135.             return resultMsg;  
  136.               
  137.         } catch (Exception e)  
  138.         {  
  139.             ResultMsg resultMsg = new ResultMsg(ResultStatusCode.SYSTEM_ERR.getErrcode(),  
  140.                     ResultStatusCode.SYSTEM_ERR.getErrmsg(), null);  
  141.             return resultMsg;  
  142.         }  
  143.     }  
  144. }  

5、运行测试

调用接口,获取生成excel后的url



直接使用excelURL下载excel文件,打开文件后如下所示



原创粉丝点击