java 复杂报表_Java+POI+模板”一:打造复杂Excel 报表
1 设计思路
Java 对于Excel 的操作一般借助于POI 类库,由于有些报表的表头比较复杂,直接用POI 控制报表的生成比较困难,这时可以先制作Excel 报表模板,而后再通过Java 调用POI 函数将用户数据写入到Excel 报表模板,最后导出到新的目标文件即可。
2 设计步骤
2.1 初始步骤
2.1.1创建Excel 报表模板
根据需要设计出Excel 报表,并保存为default.xls。如下图所示。
2.1.2创建ExcelTemplate类
Java代码
/**
* 该类实现了基于模板的导出
* 如果要导出序号,需要在excel中定义一个标识为sernums
* 如果要替换信息,需要传入一个Map,这个map中存储着要替换信息的值,在excel中通过#来开头
* 要从哪一行那一列开始替换需要定义一个标识为datas
* 如果要设定相应的样式,可以在该行使用styles完成设定,此时所有此行都使用该样式
* 如果使用defaultStyls作为表示,表示默认样式,如果没有defaultStyles使用datas行作为默认样式
*/
public class ExcelTemplate {
private ExcelTemplate() {
}
public static ExcelTemplate getInstance() {
return et;
}
}
下面是以后要用到的一些变量和常量
Java代码
/**
* 数据行标识
*/
public final static String DATA_LINE = "datas";
/**
* 默认样式标识
*/
public final static String DEFAULT_STYLE = "defaultStyles";
/**
* 行样式标识
*/
public final static String STYLE = "styles";
/**
* 插入序号样式标识
*/
public final static String SER_NUM = "sernums";
private static ExcelTemplate et = new ExcelTemplate();
private Workbook wb;
private Sheet sheet;
/**
* 数据的初始化列数
*/
private int initColIndex;
/**
* 数据的初始化行数
*/
private int initRowIndex;
/**
* 当前列数
*/
private int curColIndex;
/**
* 当前行数
*/
private int curRowIndex;
/**
* 当前行对象
*/
private Row curRow;
/**
* 最后一行的数据
*/
private int lastRowIndex;
/**
* 默认样式
*/
private CellStyle defaultStyle;
/**
* 默认行高
*/
private float rowHeight;
/**
* 存储某一方所对于的样式
*/
private Map styles;
/**
* 序号的列
*/
private int serColIndex;
2.2 读取excel报表模板的数据
Java代码
/**
* 1、读取相应的模板文档
*/
public ExcelTemplate readTemplateByClasspath(String path){
try {
wb=WorkbookFactory.create(ExcelTemplate.class.getResourceAsStream(path));
initTemplate();
} catch (InvalidFormatException e) {
e.printStackTrace();
throw new RuntimeException("InvalidFormatException, please check.");
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("The template is not exist, please check.");
}
return this;
}
public ExcelTemplate readTemplateByPath(String path){
try {
wb=WorkbookFactory.create(new File(path));
} catch (InvalidFormatException e) {
e.printStackTrace();
throw new RuntimeException("InvalidFormatException, please check.");
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("The template is not exist, please check.");
}
return this;
}
在读取报表模板的时候会初始化模板,记录模板的样式,插入数据的位置
Java代码
private void initTemplate(){
sheet=wb.getSheetAt(0);
initConfigData();
lastRowIndex = sheet.getLastRowNum();
curRow=sheet.getRow(curRowIndex);
}
/**
* 循环遍历,找到有datas字符的那个单元,记录initColIndex,initRowIndex,curColIndex,curRowIndex
* 调用initStyles()方法
* 在寻找datas字符的时候会顺便找一下sernums,如果有则记录其列号serColIndex;如果没有则调用initSer()方法,重新循环查找
*/
private void initConfigData() {
boolean findData=false;
boolean findSer = false;
for(Row row : sheet){
if(findData) break;
for(Cell c: row){
if(c.getCellType()!=Cell.CELL_TYPE_STRING) continue;
String str=c.getStringCellValue().trim();
if(str.equals(SER_NUM)){
serColIndex=c.getColumnIndex();
findSer=true;
}
if(str.equals(DATA_LINE)){
initColIndex=c.getColumnIndex();
initRowIndex=row.getRowNum();
curColIndex=initColIndex;
curRowIndex=initRowIndex;
findData=true;
break;
}
}
}
if(!findSer){
initSer();
}
initStyles();
}
/**
* 初始化序号位置
*/
private void initSer() {
for(Row row:sheet) {
for(Cell c:row) {
if(c.getCellType()!=Cell.CELL_TYPE_STRING) continue;
String str = c.getStringCellValue().trim();
if(str.equals(SER_NUM)) {
serColIndex = c.getColumnIndex();
}
}
}
}
/**
* 初始化样式信息
*/
private void initStyles(){
styles = new HashMap();
for(Row row:sheet) {
for(Cell c:row) {
if(c.getCellType()!=Cell.CELL_TYPE_STRING) continue;
String str = c.getStringCellValue().trim();
if(str.equals(DEFAULT_STYLE)) {
defaultStyle = c.getCellStyle();
rowHeight=row.getHeightInPoints();
}
if(str.equals(STYLE)||str.equals(SER_NUM)) {
styles.put(c.getColumnIndex(), c.getCellStyle());
}
}
}
}
2.3 新建excel并向其写数据
Java代码
public void writeToFile(String filepath){
FileOutputStream fos=null;
try {
fos=new FileOutputStream(filepath);
wb.write(fos);
} catch (FileNotFoundException e) {
e.printStackTrace();
throw new RuntimeException("写入的文件不存在"+e.getMessage());
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("写入数据失败"+e.getMessage());
} finally{
if(fos!=null)
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
2.4 实现Excel公共模板的第一步(实现了数据插入)
下面是创建单元格的方法,以及重载方法
Java代码
public void createCell(String value){
Cell c =curRow.createCell(curColIndex);
setCellStyle(c);
c.setCellValue(value);
curColIndex++;
}
public void createCell(int value) {
Cell c = curRow.createCell(curColIndex);
setCellStyle(c);
c.setCellValue((int)value);
curColIndex++;
}
public void createCell(Date value) {
Cell c = curRow.createCell(curColIndex);
setCellStyle(c);
c.setCellValue(value);
curColIndex++;
}
public void createCell(double value) {
Cell c = curRow.createCell(curColIndex);
setCellStyle(c);
c.setCellValue(value);
curColIndex++;
}
public void createCell(boolean value) {
Cell c = curRow.createCell(curColIndex);
setCellStyle(c);
c.setCellValue(value);
curColIndex++;
}
public void createCell(Calendar value) {
Cell c = curRow.createCell(curColIndex);
setCellStyle(c);
c.setCellValue(value);
curColIndex++;
}
上面的方法会调用setCellStyle方法来设置单元格样式
Java代码
/**
* 设置某个单元格的样式
* @param c
*/
private void setCellStyle(Cell c) {
if(styles.containsKey(c.getColumnIndex())) {
c.setCellStyle(styles.get(c.getColumnIndex()));
} else {
c.setCellStyle(defaultStyle);
}
}
createNewRow方法用于创建新的行,新的行的位置位于curRowIndex,从curRowIndex到lastRowIndex的所有行会自动向下移动一行。
Java代码
public void createNewRow(){
if(lastRowIndex>curRowIndex&&curRowIndex!=initRowIndex) {
sheet.shiftRows(curRowIndex, lastRowIndex, 1,true,true);
lastRowIndex++;
}
curRow = sheet.createRow(curRowIndex);
curRow.setHeightInPoints(rowHeight);
curRowIndex++;
curColIndex=initColIndex;
}
2.5 实现增加序号
Java代码
/**
* 插入序号,会自动找相应的序号标示的位置完成插入
*/
public void insertSer() {
int index = 1;
Row row = null;
Cell c = null;
for(int i=initRowIndex;i
row = sheet.getRow(i);
c = row.createCell(serColIndex);
setCellStyle(c);
c.setCellValue(index++);
}
}
2.6 替换模板中#开头的值
Java代码
/**
* 根据map替换相应的常量,通过Map中的值来替换#开头的值
* @param datas
*/
public void replaceFinalData(Map datas) {
if(datas==null) return;
for(Row row:sheet) {
for(Cell c:row) {
if(c.getCellType()!=Cell.CELL_TYPE_STRING) continue;
String str = c.getStringCellValue().trim();
if(str.startsWith("#")) {
if(datas.containsKey(str.substring(1))) {
c.setCellValue(datas.get(str.substring(1)));
}
}
}
}
}
3实现步骤
Java代码
@Test
public void test01() {
ExcelTemplate et = ExcelTemplate.getInstance()
.readTemplateByClasspath("/excel/default.xls");
et.createNewRow();
et.createCell("1111111");
et.createCell("aaaaaaaaaaaa");
et.createCell("a1");
et.createCell("a2a2");
et.createNewRow();
et.createCell("222222");
et.createCell("bbbbb");
et.createCell("b");
et.createCell("dbbb");
et.createNewRow();
et.createCell("3333333");
et.createCell("cccccc");
et.createCell("a1");
et.createCell(12333);
et.createNewRow();
et.createCell("4444444");
et.createCell("ddddd");
et.createCell("a1");
et.createCell("a2a2");
et.createNewRow();
et.createCell("555555");
et.createCell("eeeeee");
et.createCell("a1");
et.createCell(112);
et.createNewRow();
et.createCell("555555");
et.createCell("eeeeee");
et.createCell("a1");
et.createCell("a2a2");
et.createNewRow();
et.createCell("555555");
et.createCell("eeeeee");
et.createCell("a1");
et.createCell("a2a2");
et.createNewRow();
et.createCell("555555");
et.createCell("eeeeee");
et.createCell("a1");
et.createCell("a2a2");
et.createNewRow();
et.createCell("555555");
et.createCell("eeeeee");
et.createCell("a1");
et.createCell("a2a2");
et.createNewRow();
et.createCell("555555");
et.createCell("eeeeee");
et.createCell("a1");
et.createCell("a2a2");
et.createNewRow();
et.createCell("555555");
et.createCell("eeeeee");
et.createCell("a1");
et.createCell("a2a2");
Map datas = new HashMap();
datas.put("title","测试用户信息");
datas.put("date","2012-06-02 12:33");
datas.put("dep","昭通师专财务处");
et.replaceFinalData(datas);
et.insertSer();
et.writeToFile("d:/test/poi/test01.xls");
}
4 最后结果
java 复杂报表_Java+POI+模板”一:打造复杂Excel 报表相关推荐
- 性能碾压 POI !利用模板语法快速生成 Excel 报表
本期讲师:刘鹏 GcExcel项目组,核心开发者 Hello,大家好,本期葡萄城技术公开课,将由我来为大家带来<性能碾压 POI !利用模板语法快速生成 Excel 报表>的技术分享. 本 ...
- java formula one 用法_使用Formula One生成Excel报表-
[ 在上篇文章中,我们简单介绍了java读取word,excel和pdf文档内容 ,但在实际开发中,我们用到最多的是把数据库中数据导出excel报表形式.不仅仅简单的读取office中的数据 最近开发 ...
- java filesystem 追加_java 如何往已经存在的excel表格里面追加数据的方法
第一步.导入jar包,两个 第二步.编写程序 package cn.com.com; import java.io.FileInputStream; import java.io.FileOutput ...
- java poi excel 图表_java poi导出带图表的excel表格
1 /** 2 *导出综合得分统计3 *@paramfileName4 *@paramrequest5 *@paramresponse6 *@paramheadInfo7 *@paramdataLis ...
- java swing 导出文件_java swing (一) 导出excel文件并打开
点击XXX管理系统中的"导出Excel"按钮,然后弹出如上图,点击"保存"以后,该Excel就保存到指定路径,并且打开. 上述的动作,其实不难,主要是打开该文件 ...
- java 动态表头_java如何生成可变表头的excel
本文为大家分享了java生成可变表头excel的具体步骤,供大家参考,具体内容如下 1.实现功能: 传入一个表头和数据,将数据导入到excel中. 为了便于项目的扩展,数据传入通过泛型集合传入,获取数 ...
- POI报表入门,excel,使用事件模型解析百万数据excel报表
POI报表入门,excel 1.pom依赖: <?xml version="1.0" encoding="UTF-8"?> <project ...
- Java比较两份excel-Apache POI
1:下列代码为Java比较两份excel 或者同一份excel的两个不同的sheet每一行是否相同:同时提供模糊匹配和精准匹配两个方案可以选择.大家如果有更好的方法 欢迎大家在下面留言哦... A:读 ...
- Acey.ExcelX实例演练(1)—从GridView中导出Excel报表
Acey.ExcelX实例演练(1) -从GridView中导出Excel报表 关键词:GridView,数据绑定,Excel报表 在开发过程中我们经常遇到需要将页面中查看到的数据导出Excel的情况 ...
最新文章
- 网站压力测试工具webbench
- R构建lasso回归模型并获得最佳正则化系数
- c语言布尔 printf,fmt.Printf中的格式化动作('verb')
- java 中类的加载顺序
- 后台寻路系统的大体思路与流程
- Flex2.0实现文件上传功能(服务器为ASP.NET)
- linux yum自动挂载_Linux运维——升级系统相关漏洞
- xhtmlrenderer + iText-HTML转PDF
- 追踪监听(TraceListener)
- Mysql查看执行计划-explain
- 人工智能6.1 -- 机器学习算法篇(一)数据清洗、回归(含实践)
- netstat命令详解
- 一键开关Oracle服务
- 2018年广发证券信息技术部面试总结
- Method类及其用法
- 微信公众号图文编辑新手教程
- 2022新版PMP考试有哪些变化?
- php无法获取操作系统信息,如何获取操作系统信息
- java.sql.SQLException: Illegal conversion 非法转化
- 深度学习常用损失MSE、RMSE、MAE和MAPE
热门文章
- Nagios Web 页面声音报警
- redis主从复制实验,使用ruby
- String与StringBuffer 理解
- Silverlight Telerik控件学习:带CheckBox复选框的树形TreeView控件
- c语言数组中的字母可以相等吗,C语言数组比较
- 荣耀有鸿蒙手机吗,荣耀手机也能升鸿蒙!这5款机型用户有福了
- c语言打开当前目录下的文件_Linux下自定义文件默认打开方式
- php mysql xa_分布式事务之——MySQL对XA事务的支持
- Java基础看jvm,JAVA基础知识|java虚拟机(JVM)
- 无密码进去mysql_技术分享 | 安全地无密码登录 MySQL