Java 中jasperReport实现动态列打印的实现代码
以下代码中注释说明很清楚,希望能帮助到大家,大家参考下。
示例代码:
public ActionResult projectPrint() {
String[] printValue = null;
// 从页面中获得要查询的字段
String reqPrintValue = getRequest().getParameter("printValue");
// 没有选择则默认全打印
if (null == reqPrintValue || StringUtils.isEmpty(reqPrintValue)) {
printValue = new String[] { "pnumber", "pname", "pdepart", "pdecision", "pthrow", "plastmonth", "pfund", "ploan" };
} else {
printValue = reqPrintValue.split(",");
}
// 查询统计数据
List projectList = getEntityManager().queryPrintProjectInfo(printValue);
// 将数据转换为Map对象,换化成Map对象
List reportDataList = new ArrayList();
for (int i = 0; i < projectList.size(); i++) {
Object[] personStr = projectList.get(i);
Map reportData = new HashMap();
for (int j = 0; j < personStr.length; j++) {
reportData.put("field_" + j, String.valueOf(personStr[j]));
}
reportDataList.add(reportData);
}
int columCount = 0;// 数据列
int fieldCount = 0;// 字段列数(因为pname比较长所以想让pname比其它的列长些,故设计这个变量)
int pnameCount = -1;// 记录下pname的序号
for (int i = 0; i < printValue.length; i++) {
// pthrow下面有两列
if ("pthrow".equals(printValue[i])) {
columCount = columCount + 2;
fieldCount = fieldCount + 2;
// ploan下面也有两列
} else if ("ploan".equals(printValue[i])) {
columCount = columCount + 2;
fieldCount = fieldCount + 2;
// 故意让pname也占两列
} else if ("pname".equals(printValue[i])) {
pnameCount = i;// 记录下pname的序号
columCount = columCount + 1;
fieldCount = fieldCount + 2;
} else {
// 其它的列都占一个单位
columCount = columCount + 1;
fieldCount = fieldCount + 1;
}
}
InputStream is = null;
try {
// 从资源文件中读取报表
is = this.getClass().getResourceAsStream("/reports/project.jrxml");
JasperDesign jasperDesign = (JasperDesign) JRXmlLoader.load(is);
Map styleMap = jasperDesign.getStylesMap();
// column header 对应的样式
JRDesignStyle theaderStyle = (JRDesignStyle) styleMap.get("theader");
// column detail 对应的样式
JRDesignStyle tbodyStyle = (JRDesignStyle) styleMap.get("tboby");
// pagefoot 对应的样式
JRDesignStyle tfootStyle = (JRDesignStyle) styleMap.get("tfoot");
int _START_X_ = 20;// x轴的起始位置
int startX = _START_X_; // x轴的起始位置
// 单列的宽度
// 535是jasepreReport报表column最大的宽度
int columnWidth = 535 / fieldCount;
// 20,24,15是报表中已设置的,一定与之相同
final int columnHeadBa