java poi导出excel模板_Java编程使用POI框架模板方式导出Excel文件

package com.leftso.test

import java.io.File;

import java.io.FileOutputStream;

import java.io.InputStream;

import java.io.OutputStream;

import org.apache.poi.ss.usermodel.Cell;

import org.apache.poi.ss.usermodel.Row;

import org.apache.poi.ss.usermodel.Sheet;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ExportExcelByPOITest {

public static void main(String[] args) {

try {

File file=new File("d:/1.xlsx");

FileOutputStream fos=new FileOutputStream(file);

exportExcel(fos);

fos.flush();

fos.close();

} catch (Exception e) {

e.printStackTrace();

}

}

/**

* 测试Excel通过模板方式写入

*

* @param outputStream

* @throws Exception

*/

public static void exportExcel(OutputStream outputStream) throws Exception {

// 载入模板文件,也可以通过File的方式载入

InputStream is = Object.class.getResourceAsStream("/com/leftso/test/template.xlsx");//存放模板文件路径

// 通过模板生成Workbook

XSSFWorkbook workbook = new XSSFWorkbook(is);

// 下面进行模板填写

// 获取Excel文件的第一个sheet

Sheet sheet0 = workbook.getSheetAt(0);

// 写入title

Row row0 = sheet0.getRow(0);

Cell row0Cell0 = row0.getCell(0);

row0Cell0.setCellValue("这句话是代码填写的标题");

// 写入标签1的数据

Row row1 = sheet0.getRow(1);

Cell row1Cell;

for (int i = 1; i < 5; i++) {

row1Cell = row1.getCell(i);// 因为第一个cell是标题,数据从第二个cell开始

row1Cell.setCellValue(i + 8);

}

// 写入标签2数据

Row row2 = sheet0.getRow(2);

Cell row2Cell;

for (int i = 1; i < 5; i++) {

row2Cell = row2.getCell(i);// 因为第一个cell是标题,数据从第二个cell开始

row2Cell.setCellValue(i - 9);

}

// 注意,标签3没有填充数据

workbook.write(outputStream);

// 关闭资源

workbook.close();

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值