一,什么是poi?
1,poi
poi是用來兼容微軟文檔格式的java api,
它是apache的頂級項目之一,
也是我們在生產環境中導出excel時使用最多的庫
2,poi官方網站:
http://poi.apache.org/
說明:劉宏締的架構森林是一個專注架構的博客,地址:https://www.cnblogs.com/architectforest
對應的源碼可以訪問這里獲取: https://github.com/liuhongdi/
說明:作者:劉宏締 郵箱: 371125307@qq.com
二,演示項目的相關信息
1,項目地址:
https://github.com/liuhongdi/exportexcel
2,項目說明:
讀取數據庫中的商品數據,
保存成excel表格文件,或下載excel表格文件
3,項目結構,如圖:
三,配置文件說明:
1,pom.xml
<!--引入poi begin--> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.1.2</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.1.2</version> </dependency> <!--poi end--> <!--mybatis begin--> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.3</version> </dependency> <!--mybatis end--> <!--mysql begin--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <!--mysql end-->
說明:導入poi依賴是用來實現導出excel表格功能
2,application.properties
#mysql spring.datasource.url=jdbc:mysql://localhost:3306/store?characterEncoding=utf8&useSSL=false spring.datasource.username=root spring.datasource.password=lhddemo spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver #mybatis mybatis.mapper-locations=classpath:/mapper/*Mapper.xml mybatis.type-aliases-package=com.example.demo.mapper mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
3,數據表建表sql
CREATE TABLE `goods` ( `goodsId` int(11) NOT NULL AUTO_INCREMENT COMMENT 'id', `goodsName` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL DEFAULT '' COMMENT 'name', `subject` varchar(200) NOT NULL DEFAULT '' COMMENT '標題', `price` decimal(15,2) NOT NULL DEFAULT '0.00' COMMENT '價格', `stock` int(11) NOT NULL DEFAULT '0' COMMENT 'stock', PRIMARY KEY (`goodsId`) ) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='商品表'
四,java代碼說明
1,ExcelUtil.java
public class ExcelUtil { //save excel to a file public static void saveExcelFile( HSSFWorkbook wb, String filepath){ File file = new File(filepath); if (file.exists()) { file.delete(); } try { wb.write(new FileOutputStream(file)); } catch (Exception e) { e.printStackTrace(); } } //download a execl file public static void downExecelFile(HSSFWorkbook wb,String filename) { ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletResponse response = servletRequestAttributes.getResponse(); try { // 輸出Excel文件 OutputStream output = response.getOutputStream(); response.reset(); //設置文件頭 response.setHeader("Content-Disposition", "attchement;filename=" + new String(filename.getBytes("utf-8"), "ISO8859-1")); response.setContentType("application/msexcel"); wb.write(output); wb.close(); } catch (Exception e) { e.printStackTrace(); } } }
分別實現了把HSSFWorkbook保存成文件和下載兩個功能
2,HomeController.java
@RestController @RequestMapping("/home") public class HomeController { @Resource private GoodsMapper goodsMapper; @GetMapping("/exportexcel") public void exportExcel() { HSSFWorkbook wb = new HSSFWorkbook(); // 根據頁面index 獲取sheet頁 HSSFSheet sheet = wb.createSheet("商品基本信息"); createTitle(wb,sheet); //設置列寬度 List<Goods> goodsList = goodsMapper.selectAllGoods(); //表內容從第二行開始 int i=1; for (Goods goodsOne : goodsList) { HSSFRow row = sheet.createRow(i + 1); //創建HSSFCell對象 設置單元格的值 row.createCell(0).setCellValue(goodsOne.getGoodsId()); row.createCell(1).setCellValue(goodsOne.getGoodsName()); row.createCell(2).setCellValue(goodsOne.getSubject()); row.createCell(3).setCellValue(goodsOne.getStock()); i++; } //保存成文件 ExcelUtil.saveExcelFile(wb,"/data/file/html/商品信息.xls"); //下載文件 ExcelUtil.downExecelFile(wb,"商品信息.xls"); } //創建標題和表頭 private void createTitle(HSSFWorkbook workbook,HSSFSheet sheet){ //用CellRangeAddress合並單元格,在這里作為sheet中的標題 //參數1:起始行 參數2:終止行 參數3:起始列 參數4:終止列 CellRangeAddress region1 = new CellRangeAddress(0, 0, 0, 3); sheet.addMergedRegion(region1); HSSFRow row_title = sheet.createRow(0); row_title.setHeightInPoints(26); HSSFCell cell_title; cell_title = row_title.createCell(0); cell_title.setCellValue("商品信息表"); //設置標題樣式:居中加粗 HSSFCellStyle style_title = workbook.createCellStyle(); HSSFFont font_title = workbook.createFont(); font_title.setBold(true); font_title.setFontHeightInPoints((short) 20); font_title.setColor(HSSFColor.HSSFColorPredefined.BLUE.getIndex()); style_title.setFont(font_title); style_title.setAlignment(HorizontalAlignment.CENTER); style_title.setVerticalAlignment(VerticalAlignment.CENTER); cell_title.setCellStyle(style_title); //以下為表頭 HSSFRow row = sheet.createRow(1); //設置行高 row.setHeightInPoints(18); //設置列寬度 sheet.setColumnWidth(0,10*256); sheet.setColumnWidth(1,30*256); sheet.setColumnWidth(2,30*256); sheet.setColumnWidth(3,10*256); //設置樣式:居中加粗 HSSFCellStyle style = workbook.createCellStyle(); HSSFFont font = workbook.createFont(); font.setBold(true); font.setColor(HSSFColor.HSSFColorPredefined.GREEN.getIndex()); style.setFont(font); style.setAlignment(HorizontalAlignment.CENTER); style.setVerticalAlignment(VerticalAlignment.CENTER); //添加4個字段 HSSFCell cell; cell = row.createCell(0); cell.setCellValue("id"); cell.setCellStyle(style); cell = row.createCell(1); cell.setCellValue("商品名稱"); cell.setCellStyle(style); cell = row.createCell(2); cell.setCellValue("商品描述"); cell.setCellStyle(style); cell = row.createCell(3); cell.setCellValue("庫存數量"); cell.setCellStyle(style); } }
說明:注意HSSFCellStyle是用來定義表格樣式的類,
我們需要借助它來實現表格中文字的樣式,
包括:HSSFFont:字體樣式,
HorizontalAlignment 水平對齊
VerticalAlignment 垂直對齊
HSSFColor:文字顏色
說明:保存成excel文件和下載excel文件兩功能沒有關聯,
這里只為演示,大家按需求使用
3,mybatis用到的mapper類和mapper xml文件,
商品的對象類: Goods.java
比較簡單,參見github上的代碼即可,
不再貼出
五,測試效果
1,下載excel
訪問地址:
http://127.0.0.1:8080/home/exportexcel
下載的excel表格內容如圖:
可以看到我們配置的樣式已生效
六,查看spring boot的版本
. ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.3.1.RELEASE)