赞
踩
工作中经常要用到excel的导出,所以参考其他人的demo写了一个导出excel的基础代码。如果以后再需要用的时候,直接拿来修改下就能直接使用。
参考博文地址:https://blog.csdn.net/phil_jing/article/details/78307819
以下是maven依赖
- <dependency>
- <groupId>org.apache.poi</groupId>
- <artifactId>poi</artifactId>
- <version>3.17</version>
- </dependency>
- <dependency>
- <groupId>org.apache.poi</groupId>
- <artifactId>poi-ooxml</artifactId>
- <version>3.17</version>
- </dependency>
工具包
- <dependency>
- <groupId>org.apache.commons</groupId>
- <artifactId>commons-lang3</artifactId>
- <version>3.9</version>
- </dependency>
以下是导出代码实现
- package com.example.demo.utils;
-
- import org.apache.commons.lang3.StringUtils;
- import org.apache.poi.ss.util.CellRangeAddress;
- import org.apache.poi.xssf.usermodel.XSSFWorkbook;
- import org.apache.commons.lang3.time.FastDateFormat;
- import java.util.Collection;
- import java.util.Date;
- import java.util.Iterator;
- import java.util.Map;
- import java.util.regex.Matcher;
- import java.util.regex.Pattern;
-
- import org.apache.poi.ss.usermodel.*;
- import org.apache.poi.ss.usermodel.Cell;
- import org.apache.poi.ss.usermodel.CellStyle;
- import org.apache.poi.ss.usermodel.FillPatternType;
- import org.apache.poi.ss.usermodel.Font;
- import org.apache.poi.ss.usermodel.HorizontalAlignment;
- import org.apache.poi.ss.usermodel.IndexedColors;
- import org.apache.poi.ss.usermodel.Row;
- import org.apache.poi.ss.usermodel.Sheet;
- import org.apache.poi.ss.usermodel.VerticalAlignment;
- import org.apache.poi.ss.usermodel.Workbook;
-
- public class ExportExcel {
-
- /**
- * excel导出
- * @param sheetName sheet名称
- * @param title 标题
- * @param headers 表头
- * @param columns 字段名称
- * @param dataset 数据集合
- * @param pattern 日期格式
- * @return Workbook
- */
- public static Workbook exportExcel(String sheetName, String title, String[] headers, String[] columns,
- Collection<Map<String, Object>> dataset, String pattern){
- // 创建excel工作簿
- Workbook workbook = new XSSFWorkbook();
- // 创建第一个sheet(页),并命名
- Sheet sheet = workbook.createSheet(sheetName);
-
- // -----------------表格标题行样式-----------------
- CellStyle titleStyle = workbook.createCellStyle();
- // 设置这些样式
- titleStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); // 填充颜色
- titleStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); // 填充样式
- titleStyle.setAlignment(HorizontalAlignment.CENTER); // 水平居中
- titleStyle.setVerticalAlignment(VerticalAlignment.CENTER); //垂直居中
- titleStyle.setBorderBottom(BorderStyle.THIN);
- titleStyle.setBorderLeft(BorderStyle.THIN);
- titleStyle.setBorderRight(BorderStyle.THIN);
- titleStyle.setBorderTop(BorderStyle.THIN);
- // 生成一个字体
- Font font = workbook.createFont();
- font.setColor(IndexedColors.WHITE.getIndex());
- font.setFontHeightInPoints((short) 12);
- font.setBold(true);
- // font.setBoldweight((short)700));
- // 把字体应用到当前的样式
- titleStyle.setFont(font);
-
- // ----------------样式2 内容的背景----------------
- CellStyle style2 = workbook.createCellStyle();
- style2.setFillForegroundColor(IndexedColors.WHITE.getIndex());
- style2.setFillPattern(FillPatternType.SOLID_FOREGROUND);
- style2.setBorderBottom(BorderStyle.THIN);
- style2.setBorderLeft(BorderStyle.THIN);
- style2.setBorderRight(BorderStyle.THIN);
- style2.setBorderTop(BorderStyle.THIN);
- style2.setAlignment(HorizontalAlignment.CENTER);
- style2.setVerticalAlignment(VerticalAlignment.CENTER);
- // 生成另一个字体
- Font font2 = workbook.createFont();
- font.setBold(true);
- // font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
- // 把字体应用到当前的样式
- style2.setFont(font2);
-
- int rowCount = 0; // 起始行号
- Row row;
- // ------------设置首行标题标题--------------
- if (StringUtils.isNotEmpty(title)){
- // 如果有标题
- row = sheet.createRow(rowCount);
- Cell cell = row.createCell(rowCount);
- cell.setCellValue(title);
- cell.setCellStyle(titleStyle);
- //合并单元格
- CellRangeAddress region = new CellRangeAddress(rowCount, rowCount, 0, headers.length-1);
- sheet.addMergedRegion(region);
- rowCount++;
- }
-
- // ----------------表头------------------
- row = sheet.createRow(rowCount);
- //
- for (int i = 0; i < headers.length; i++) {
- Cell cell = row.createCell(i);
- cell.setCellStyle(titleStyle);
- // 富文本字符串:用于同一单元格内容展示不用样式
- // RichTextString text = new XSSFRichTextString(headers[i]);
- cell.setCellValue(headers[i]);
- }
- rowCount++;
-
- // --------------单元格数据----------------
- if(StringUtils.isEmpty(pattern)) {
- pattern = "yyyy/MM/dd";
- }
- FastDateFormat instance = FastDateFormat.getInstance(pattern);
- // 遍历集合数据,产生数据行
- Iterator<Map<String, Object>> it = dataset.iterator(); // 多个Map集合
- int count = 0;
- while (it.hasNext()) {
- row = sheet.createRow(rowCount);
- Map<String, Object> map = it.next();
- count = headers.length < columns.length ? headers.length : columns.length;
- for (int i = 0; i < count; i++) {
- Cell cell = row.createCell(i);
- cell.setCellStyle(style2);
- try {
- Object value = map.get(columns[i]);
- // 判断值的类型后进行强制类型转换
- String textValue = null;
- if (value instanceof Date) {
- Date date = (Date) value;
- textValue = instance.format(date);
- }else {
- // 其它数据类型都当作字符串简单处理
- if (value != null) {
- textValue = value.toString();
- } else {
- textValue = "";
- }
- }
- // 利用正则表达式判断textValue是否全部由数字组成
- if (textValue != null) {
- Pattern p = Pattern.compile("^//d+(//.//d+)?$");
- Matcher matcher = p.matcher(textValue);
- if (matcher.matches()) {
- // 是数字当作double处理
- cell.setCellValue(Double.parseDouble(textValue));
- } else {
- cell.setCellValue(textValue);
- cell.setCellStyle(style2);
- }
- }
- } catch (SecurityException e) {
- e.printStackTrace();
- }
- }
- rowCount++;
- }
- return workbook;
- }
- }
控制层调用
- package com.example.demo.controller;
-
- import com.example.demo.model.Bean;
- import com.example.demo.utils.ExportExcel;
- import org.apache.poi.ss.usermodel.Workbook;
- import org.springframework.util.StringUtils;
- import org.springframework.web.bind.annotation.*;
-
- import javax.servlet.http.HttpServletResponse;
- import java.time.LocalTime;
- import java.util.*;
-
- @RestController
- public class TestController {
-
- private static String EXPORT_XLSX_FILE_SUFFIX = ".xlsx";
- private static String EXPORT_XLS_FILE_SUFFIX = ".xls";
-
- /**
- * 导出
- */
- @RequestMapping(value = "/export")
- public void getExcel1(@RequestParam Map<String, Object> map, HttpServletResponse response) throws Exception {
- LocalTime localTime1 = LocalTime.now();
- System.out.println("开始时间:" + localTime1);
- //查询条件
- System.out.println((String) map.get("name"));
- //
- List<Bean> beanList = new ArrayList<>();
- for (int i = 0; i<10000; i++){
- Bean bean1 = new Bean();
- bean1.setAttribute("属性" + i);
- bean1.setName("字段" + i);
- bean1.setLength(i);
- bean1.setType("类型" + i);
- bean1.setNote("注释" + i);
- beanList.add(bean1);
- }
- List<Map<String,Object>> list = new ArrayList<>();
- for (Bean bean : beanList) {
- Map<String,Object> hashMap = new HashMap<>();
- //
- hashMap.put("attribute",bean.getAttribute());
- hashMap.put("name",bean.getName());
- hashMap.put("length",bean.getLength());
- hashMap.put("type",bean.getType());
- hashMap.put("note",bean.getNote());
- //
- list.add(hashMap);
- }
-
- String sheetName = "sheet1";
- String title1 = "标题"; // 标题
- String[] title2 = {"属性", "字段", "长度","类型","注释"}; // 表头
- String[] columns = {"attribute", "name", "length","type","note"}; // 字段
- String pattern = "yyyy/MM/dd"; // 日期格式
- //
- String excelType;
- if(StringUtils.isEmpty(map.get("excel_type"))) {
- excelType = EXPORT_XLSX_FILE_SUFFIX;
- } else {
- excelType = (String) map.get("excel_type");
- }
- Workbook workbook = ExportExcel.exportExcel(sheetName,title1,title2,columns,list,pattern);
- response.setHeader("Content-type", "application/vnd.ms-excel");
- response.setCharacterEncoding("UTF-8");
- response.setHeader("Content-Disposition", "attachment;filename=" + System.currentTimeMillis() + excelType);
- workbook.write(response.getOutputStream());
- workbook.close();
- //
- LocalTime localTime2 = LocalTime.now();
- System.out.println("结束时间:" + localTime2);
- }
-
- }
项目启动后,在浏览器地址栏输入:localhost:8080/export?excel_type=.xls&name=小明
导出1w条数据所用时间大概为3-4秒
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。