Java 实现将数据导出为Excel表格

 原文地址

  • 需求:将符合查询条件的MySQL数据导出为Excel
  1. 导入poi依赖
    <!-- poi文件工具 -->
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi</artifactId>
        <version>3.14</version>
    </dependency>
  2. 查询数据,将数据封装为一个列表(第一个参数)
  3. 需要为要导出的数据新建一个模板template,要和数据字段一一对应(第二个参数)
  4. 准备一个放Excel的文件目录(第三个参数)



  •  工具类
/*
    导出Excel工具类
 */
public class ExcelUtils {

    /**
     * @param list     表格内容结果
     * @param template 模板位置
     * @param basepath 文件导出路径
     * @throws Exception
     */
    public static String CreateExcel(List list, String template, String basepath) throws Exception {
        //获得模板
        FileInputStream inputStream = new FileInputStream(template);
        //打开模板
        XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
        //获得名字为sheet的工作本对象,这个是看你的模板工作表的名字
        XSSFSheet sheet = workbook.getSheet("sheet1");
        //因为是模板,第一行有标题了,我们直接在第二行对应模板第一行插入数据即可
        //  在第二行插数据
        for (int i = 0; i < list.size(); i++) {
            //获得第二行
            XSSFRow row = sheet.createRow(i + 1);
            //通过反射获得这个对象的属性字段数组
            Field[] Fields = list.get(i).getClass().getDeclaredFields();
            int a = 0;
            for (Field field : Fields) {
                //加这个才可以访问私有的属性
                field.setAccessible(true);
                //通过get方法得到value,等同于class.get**()
                Object o = field.get(list.get(i));
                //给改行的第0列赋值,后面a++,依次赋值
                XSSFCell cell = row.createCell(a);
                cell.setCellValue(String.valueOf(o));
                a++;
            }
        }
        //设置文件导出的保存路径
        File dir = new File(basepath);
        //判断当前目录是否存在
        if (!dir.exists()) {
            //目录不存在,需要创建
            dir.mkdirs();
        }
        // 为导出文件命名(时间+模板名称)
        template = template.substring(template.lastIndexOf("\\") + 1);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String time = dateFormat.format(new Date());
        File file = new File(dir, time + template);
        //创建文件
        file.createNewFile();
        //拿到文件的输出流
        FileOutputStream fileOutputStream = FileUtils.openOutputStream(file);
        //调用工作簿的write方法把这个流写出去
        workbook.write(fileOutputStream);
        return file.toString();
    }
}
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值