Java编程中使用POI框架以模板方式导出Excel文件,适合Excel比较复杂的情况
1.引入包,以下是通过maven方式引入必须依赖
测试模板如下:

3.Java代码
![模板生成Excel]()
至此已经完成Java编程中通过Excel模板方式导出Excel报表文件
1.引入包,以下是通过maven方式引入必须依赖
<!-- POI support -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.15</version>
</dependency>
<!-- support xlsx,docx.. -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.15</version>
</dependency>
<!-- /POI support -->
2.创建一个Excel文件作为模板,(根据自己需求定)测试模板如下:

3.Java代码
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();
}
}
4.执行Java代码中的main方法,然后去D盘查看生成文件如下:至此已经完成Java编程中通过Excel模板方式导出Excel报表文件
版权申明:本文为博主原创文章,未经博主允许不得转载。
https://www.leftso.com/blog/96.html
时效提示:本文最后更新于【 2017-03-10 21:07:00 】,某些文章具有时效性,若有错误或已失效,请在下方留言。
时效提示:本文最后更新于【 2017-03-10 21:07:00 】,某些文章具有时效性,若有错误或已失效,请在下方留言。
评论区域
评论功能已关闭. 提示:评论功能虽已关闭,关闭之前的评论仍然会展示。