Java 数据导出到excel 封装工具类

个人记录 写入博客 以备不时之需。假使搬运 请著明出处 直接上代码:
引入poi相关包

	   <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.8</version>
        </dependency>

工具类

package cn.stephen.study.demoproject.util;


import org.apache.poi.hssf.usermodel.*;
import org.springframework.util.CollectionUtils;

import java.io.FileOutputStream;
import java.util.List;

/**
 * @program: demo
 * @description:
 * @author: 王志伟
 * @create: 2020-05-13 13:12
 * <p>
 * 导出成Excel文件用
 **/
public class ExcelUtil {

    /**
     * 创建excel文档,
     *
     * @param list 数据
     * @param tableName 文件名
     * @param tableHead  列名
     */
    public static HSSFWorkbook createWorkBook(List<List<Object>> list, String tableName, List<String> tableHead) {

        // 创建excel工作簿
        HSSFWorkbook wb = new HSSFWorkbook();
        // 第二步,在webbook中添加一个sheet,对应Excel文件中的sheet
        HSSFSheet sheet = wb.createSheet(tableName);
        // 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
        HSSFRow row = sheet.createRow((int) 0);
        // 第四步,创建单元格,并设置值表头 设置表头居中
        HSSFCellStyle styleHead = wb.createCellStyle();

        HSSFFont font = wb.createFont();
        font.setFontName("仿宋_GB2312");
        font.setFontHeightInPoints((short) 12);//设置字体大小
        styleHead.setFont(font);//选择需要用到的字体格式

//        styleHead.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式

        //创建表头
        int headCellIndex = 0;
        for (String item : tableHead) {
            HSSFCell cell = row.createCell((short) headCellIndex++);
            cell.setCellValue(item);
            cell.setCellStyle(styleHead);
        }

        if (CollectionUtils.isEmpty(list)) {
            return wb;
        }

        HSSFCellStyle styleContent = wb.createCellStyle();

        font = wb.createFont();
        font.setFontName("仿宋_GB2312");
        font.setFontHeightInPoints((short) 10);//设置字体大小
//        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);//粗体显示
        styleContent.setFont(font);//选择需要用到的字体格式

        for (int i = 0; i < list.size(); i++) {
            row = sheet.createRow((int) i + 1);
            // 第四步,创建单元格,并设置值
            int index = 0;
            for (Object item : list.get(i)) {
                HSSFCell cell = row.createCell((short) index++);
                if (item != null) {
                    cell.setCellValue(item.toString());
                } else {
                    cell.setCellValue("");
                }
                cell.setCellStyle(styleContent);
            }
        }
        return wb;
    }

	//外部调用方法
    public static void returnTable(List<List<Object>> list, String tableName, List<String> tableHead) {
        HSSFWorkbook wb = createWorkBook(list, tableName, tableHead);
        returnTable(wb, tableName);
    }

	//导出地址
    public static void returnTable(HSSFWorkbook wb, String tableName) {
        try {
            FileOutputStream fout = new FileOutputStream("导出本地地址" + tableName + ".xls");
            wb.write(fout);
            fout.close();
        } catch (Exception e) {
            throw new RuntimeException("系统异常");
        }
    }

}

调用方法 Controller

 @ApiOperation(value = "导出")
   @RequestMapping(value = "/downLoad",method = RequestMethod.GET)
   public Boolean downLoad() {
       //设置表头
       List<String> headList = new ArrayList<>();
       headList.add("账号");
       headList.add("密码");
       headList.add("邮箱");
       headList.add("姓名");
       headList.add("手机");
       headList.add("备注");
   	//表名
       SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
       String codedFileName = sdf.format(new Date()) + "导出文件名";
       //数据集合
       List<List<Object>> rows = new ArrayList<>();
       //数据库内容
       List<UserDto> userDtos = userService.getAll();
       userDtos.stream().forEach(e->{
           List<Object> row = new ArrayList<>();
           //数据字段要和表头字段一一对应
           //账号
           row.add(e.getAccount());
           //密码
           row.add(e.getPassword());
           //邮箱
           row.add(e.getEmail());
           //姓名
           row.add(e.getUserName());
           //手机
           row.add(e.getPhone());
           //备注
           row.add(e.getMemo());

           rows.add(row);
       });
       ExcelUtil.returnTable(rows,codedFileName,headList);
       return true;
   }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值