文章目录
itextpdf 表格跨行跨列与可视化图表
效果图
普通表格一(表头背景色)
普通表格二 (隔列变色)
表格跨行跨列
可视化图表
饼图
柱状图
折线图
使用示例
普通表格一(表头背景色)
PdfUtil.addLevel2Title(doc, "对外投资信息");
PdfUtil.Table(7, textFont, new TableDataUtil()
.add(RowData.add("序号", "名称", "法定代表人", "注册资金", "注册号", "成立日期", "地址"))
.addList(GetData.get(desensitization, result, Compoent.INVESTMENTLIST, "NO", "InvestName", "Legal", "RegCapital", "EntRegNo", "EstDate", "RegAddress"))
.toList(), doc);
普通表格二 (隔列变色)
PdfUtil.addLevel2Title(doc, "社保基本信息");
PdfUtil.TableBuleColspan(4, textFont, new TableDataUtil()
.add(RowData.add("社保单位编号", GetData.get(result, Compoent.INHFSOCIALSECURITY, "SocialSecurityNo", desensitization), "投保起始年", GetData.get(result, Compoent.INHFSOCIALSECURITY, "InsuredYear")))
.add(RowData.add("投保起始月", GetData.get(result, Compoent.INHFSOCIALSECURITY, "InsuredMonth"), "当前状态", GetData.get(result, Compoent.INHFSOCIALSECURITY, "CurrentState")))
.add(RowData.add("参保总人数", GetData.get(result, Compoent.INHFSOCIALSECURITY, "TotalCNT"), "养老参保人数", GetData.get(result, Compoent.INHFSOCIALSECURITY, "EICNT")))
.add(RowData.add("医疗参保人数", GetData.get(result, Compoent.INHFSOCIALSECURITY, "MICNT"), "工伤参保人数", GetData.get(result, Compoent.INHFSOCIALSECURITY, "IICNT")))
.add(RowData.add("失业参保人数", GetData.get(result, Compoent.INHFSOCIALSECURITY, "UICNT")))
.toList(), doc, new int[]{5}, new int[]{2}, new int[]{3});
表格跨行跨列
PdfUtil.TableBlueColRowSpan(4, textFont, new TableDataUtil()
.add(RowData.add("科目", "报表年份"))
.add(balanceSheetKeys)
.addList(RowData.add(balanceSheetDataGroup, (data) -> {
List<List<String>> res = new ArrayList<>();
data.forEach((k, v) -> {
List<String> row = new ArrayList<>();
row.add(k);
Map<String, String> kv = v.stream().collect(Collectors.toMap(key -> String.valueOf(key.get("PeriodYear")), value -> String.valueOf(value.get("ClosingBalanceAsset"))));
balanceSheetKeysGroup.keySet().forEach(i -> {
row.add(Optional.ofNullable(kv.get(i)).orElse(""));
});
if (row.size() < 4) {
for (int i = row.size() - 1; i < 3; i++) {
row.add("");
}
}
res.add(row);
});
return res;
}))
.toList(), doc, new int[][]{{1}, {1}}, new int[][]{{2}, {1}}, new int[][]{{3}, {2}});
可视化图表
饼图
PdfPTable table = new PdfPTable(2);
table.setTotalWidth(530);
table.setLockedWidth(true);
PdfPCell leftImage = new PdfPCell();
bos = new ByteArrayOutputStream();
ChartUtils.writeChartAsJPEG(bos, ChartUtil.pieChart(String.join("", balanceSheetChartDataGroup.keySet()) + "资产结构", balanceSheetPieData), 400, 400);
image = Image.getInstance(bos.toByteArray());
image.scalePercent(60);
leftImage.addElement(image);
leftImage.disableBorderSide(-1);
table.addCell(leftImage);
柱状图
imageBaos = new ByteArrayOutputStream();
ChartUtils.writeChartAsJPEG(imageBaos, ChartUtil.barChart("", "", "", balanceSheetBarChartDataset, "{2}%"), 850, 330);
chartImage = Image.getInstance(imageBaos.toByteArray());
chartImage.scalePercent(60);
doc.add(chartImage);
折线图
ChartUtils.writeChartAsJPEG(imageBaos, ChartUtil.lineChart("用水量(立方)", "", "", waterLineDataset, CategoryLabelPositions.UP_90), 850, 430);
chartImage = Image.getInstance(imageBaos.toByteArray());
chartImage.scalePercent(60);
doc.add(chartImage);
工具类源码
依赖包
- itextpdf 5.5.6
- jfreechart 1.5.3
大家根据实际使用场景删除代码
PdfUtil
static class PdfUtil {
public static void addLevel1Title(Document doc, String title) throws DocumentException {
Paragraph p1 = new Paragraph(title, secondTitleFont);
p1.setAlignment(Element.ALIGN_CENTER);
doc.add(p1);
}
public static void addLevel2Title(Document doc, String title) throws DocumentException {
Paragraph p1 = new Paragraph(title, threeTitleFont);
p1.setAlignment(Element.ALIGN_LEFT);
p1.setSpacingAfter(8);
doc.add(p1);
}
public static void addOtherContent(Document doc, String content, int alignment, Font fontSize, float spacingAfter) throws DocumentException {
Paragraph p1 = new Paragraph(content, fontSize);
p1.setAlignment(alignment);
p1.setSpacingAfter(spacingAfter);
doc.add(p1);
}
public static void addLevel2Title(Document doc, String title, boolean newPage) throws DocumentException {
doc.newPage();
Paragraph p1 = new Paragraph(title, threeTitleFont);
p1.setAlignment(Element.ALIGN_LEFT);
p1.setSpacingAfter(8);
doc.add(p1);
}
/**
* 生成一个表格
*
* @param total 总列数
* @param textFont 字体
* @param data 表格数据 X行 Y列
* @param doc PDF文档对象
* @throws DocumentException
* @author hou_fx
*/
public static void Table(int total, Font textFont, List<List<String>> data, Document doc) throws DocumentException {
// 创建一个有N列的表格
PdfPTable table = new PdfPTable(total);
table.setPaddingTop(20);
table.setSpacingAfter(20);
table.setTotalWidth(530); //设置列宽
table.setLockedWidth(true); //锁定列宽
PdfPCell cell;
for (int i = 0; i < data.size(); i++) { //遍历数据行 每个数据行都是一个list
Iterator<String> it = data.get(i).iterator();
while (it.hasNext()) { //遍历每行数据,每个数据都是一个单元格
String text = it.next();
cell = new PdfPCell(new Phrase(text, textFont));
//表头背景色
if (i == 0) {
cell = new PdfPCell(new Phrase(text, textFontBold));
cell.setBackgroundColor(new BaseColor(199, 217, 241));
}
cell.setMinimumHeight(17); //设置单元格高度
cell.setUseAscender(true); //设置可以居中
cell.setHorizontalAlignment(i == 0 ? Element.ALIGN_CENTER : Element.ALIGN_LEFT); //表头居中,其余左对齐
cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //设置垂直居中
table.addCell(cell);
}
}
doc.add(table);
}
public static void TableNoAfter(int total, Font textFont, List<List<String>> data, Document doc) throws DocumentException {
// 创建一个有N列的表格
PdfPTable table = new PdfPTable(total);
table.setPaddingTop(20);
table.setTotalWidth(530); //设置列宽
table.setLockedWidth(true); //锁定列宽
PdfPCell cell;
for (int i = 0; i < data.size(); i++) { //遍历数据行 每个数据行都是一个list
Iterator<String> it = data.get(i).iterator();
while (it.hasNext()) { //遍历每行数据,每个数据都是一个单元格
String text = it.next();
cell = new PdfPCell(new Phrase(text, textFont));
//表头背景色
if (i == 0) {
cell = new PdfPCell(new Phrase(text, textFontBold));
cell.setBackgroundColor(new BaseColor(199, 217, 241));
}
cell.setMinimumHeight(17); //设置单元格高度
cell.setUseAscender(true); //设置可以居中
cell.setHorizontalAlignment(i == 0 ? Element.ALIGN_CENTER : Element.ALIGN_LEFT); //表头居中,其余左对齐
cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //设置垂直居中
table.addCell(cell);
}
}
doc.add(table);
}
public static void TableNoPadding(int total, Font textFont, List<List<String>> data, Document doc) throws DocumentException {
// 创建一个有N列的表格
PdfPTable table = new PdfPTable(total);
table.setTotalWidth(530); //设置列宽
table.setLockedWidth(true); //锁定列宽
PdfPCell cell;
for (int i = 0; i < data.size(); i++) { //遍历数据行 每个数据行都是一个list
Iterator<String> it = data.get(i).iterator();
while (it.hasNext()) { //遍历每行数据,每个数据都是一个单元格
String text = it.next();
cell = new PdfPCell(new Phrase(text, textFont));
cell.setMinimumHeight(17); //设置单元格高度
cell.setUseAscender(true); //设置可以居中
cell.setHorizontalAlignment(Element.ALIGN_LEFT); //表头居中,其余左对齐
cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //设置垂直居中
table.addCell(cell);
}
}
doc.add(table);
}
public static void TableNoPaddingTop(int total, Font textFont, List<List<String>> data, Document doc) throws DocumentException {
// 创建一个有N列的表格
PdfPTable table = new PdfPTable(total);
table.setPaddingTop(0.0f);
table.setSpacingAfter(0.0f);
table.setTotalWidth(530); //设置列宽
table.setLockedWidth(true); //锁定列宽
PdfPCell cell;
for (int i = 0; i < data.size(); i++) { //遍历数据行 每个数据行都是一个list
Iterator<String> it = data.get(i).iterator();
while (it.hasNext()) { //遍历每行数据,每个数据都是一个单元格
String text = it.next();
cell = new PdfPCell(new Phrase(text, textFont));
if (i == 0) {
cell = new PdfPCell(new Phrase(text, textFontBold));
cell.setBackgroundColor(new BaseColor(199, 217, 241));
}
cell.setMinimumHeight(17); //设置单元格高度
cell.setUseAscender(true); //设置可以居中
//表头背景色
cell.setHorizontalAlignment(i == 0 ? Element.ALIGN_CENTER : Element.ALIGN_LEFT); //表头居中,其余左对齐
cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //设置垂直居中
table.addCell(cell);
}
}
doc.add(table);
}
public static int appearNumber(String srcText, String findText) {
int count = 0;
Pattern p = Pattern.compile(findText);
Matcher m = p.matcher(srcText);
while (m.find()) {
count++;
}
return count;
}
/**
* 生成一个表格
*
* @param total 总列数
* @param textFont 字体
* @param data 表格数据 X行 Y列
* @param doc PDF文档对象
* @throws DocumentException
* @author hou_fx
*/
public static void TableBule(int total, Font textFont, List<List<String>> data, Document doc) throws DocumentException {
// 创建一个有N列的表格
PdfPTable table = new PdfPTable(total);
table.setPaddingTop(20);
table.setSpacingAfter(20);
table.setTotalWidth(530); //设置列宽
table.setLockedWidth(true); //锁定列宽
PdfPCell cell;
for (int i = 0; i < data.size(); i++) { //遍历数据行 每个数据行都是一个list
int count = 0;
for (int j = 0; j < data.get(i).size(); j++) {
cell = new PdfPCell(new Phrase(data.get(i).get(j), textFont));
//第一个单元格背景色
if (count % 2 == 0) {
cell = new PdfPCell(new Phrase(data.get(i).get(j), textFontBold));
cell.setBackgroundColor(new BaseColor(199, 217, 241));
}
cell.setMinimumHeight(17); //设置单元格高度
cell.setUseAscender(true); //设置可以居中
cell.setHorizontalAlignment(Element.ALIGN_LEFT); //左对齐
cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //设置垂直居中
table.addCell(cell);
count++;
}
}
doc.add(table);
}
/**
* 生成一个表格
*
* @param total 总列数
* @param textFont 字体
* @param data 表格数据 X行 Y列
* @param doc PDF文档对象
* @param colspan 第几列
* @param rowspan 第几行
* @param number 跨几列
* @throws DocumentException
* @author hou_fx
*/
public static void TableBuleColspan(int total, Font textFont, List<List<String>> data, Document doc, int[] rowspan, int[] colspan, int[] number) throws DocumentException {
// 创建一个有N列的表格
PdfPTable table = new PdfPTable(total);
table.setPaddingTop(20);
table.setSpacingAfter(20);
table.setTotalWidth(530); //设置列宽
table.setLockedWidth(true); //锁定列宽
PdfPCell cell;
//数组下标
int cos = 0;
for (int i = 0; i < data.size(); i++) { //遍历数据行 每个数据行都是一个list
int count = 0;
for (int j = 0; j < data.get(i).size(); j++) {
cell = new PdfPCell(new Phrase(data.get(i).get(j), textFont));
//第一个单元格背景色
if (j % 2 == 0) {
cell = new PdfPCell(new Phrase(data.get(i).get(j), textFontBold));
cell.setBackgroundColor(new BaseColor(199, 217, 241)); //173,216,230
}
cell.setMinimumHeight(17); //设置单元格高度
cell.setUseAscender(true); //设置可以居中
if (cos < rowspan.length && i == rowspan[cos] - 1 && count == colspan[cos] - 1) {
cell.setColspan(number[cos]);//跨单元格
cos++;
}
cell.setHorizontalAlignment(Element.ALIGN_LEFT); //左对齐
cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //设置垂直居中
table.addCell(cell);
count++;
}
}
doc.add(table);
}
/**
* 生成一个表格
*
* @param total 总列数
* @param textFont 字体
* @param data 表格数据 X行 Y列
* @param doc PDF文档对象
* @param colspan 第几列 [][] 0 跨列 1 跨行
* @param rowspan 第几行 [][] 0 跨列 1 跨行
* @param number 跨几列 [][] 0 跨列 1 跨行
* @throws DocumentException
* @author hou_fx
*/
public static void TableBlueColRowSpan(int total, Font textFont, List<List<String>> data, Document doc, int[][] rowspan, int[][] colspan, int[][] number) throws DocumentException {
// 创建一个有N列的表格
PdfPTable table = new PdfPTable(total);
table.setPaddingTop(20);
table.setSpacingAfter(20);
table.setTotalWidth(530); //设置列宽
table.setLockedWidth(true); //锁定列宽
PdfPCell cell;
for (int i = 0, cos = 0, ros = 0; i < data.size(); i++) {
for (int j = 0; j < data.get(i).size(); j++) {
cell = new PdfPCell(new Phrase(data.get(i).get(j), textFont));
if (total != data.get(i).size()) {
cell = new PdfPCell(new Phrase(data.get(i).get(j), textFontBold));
cell.setBackgroundColor(new BaseColor(199, 217, 241)); //173,216,230
}
if (data.get(i).get(j).contains("合计") || data.get(i).get(j).contains("总计")) {
cell.setBackgroundColor(new BaseColor(79, 129, 189)); //173,216,230
}
cell.setMinimumHeight(17); //设置单元格高度
cell.setUseAscender(true); //设置可以居中
cell.setHorizontalAlignment(Element.ALIGN_CENTER); //左对齐
cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //设置垂直居中
if (cos < rowspan[0].length && i == rowspan[0][cos] - 1 && j == colspan[0][cos] - 1) {
cell.setColspan(number[0][cos]);
cos++;
}
if (ros < rowspan[1].length && i == rowspan[1][ros] - 1 && j == colspan[1][ros] - 1) {
cell.setRowspan(number[1][ros]);
ros++;
}
table.addCell(cell);
}
}
doc.add(table);
}
/**
* 生成一个表格
*
* @param total 总列数
* @param textFont 字体
* @param data 表格数据 X行 Y列
* @param doc PDF文档对象
* @param colspan 第几列
* @param rowspan 第几行
* @param number 跨几列
* @throws DocumentException
* @author hou_fx
*/
public static void TableColspan(int total, Font textFont, List<List<String>> data, Document doc, int[] rowspan, int[] colspan, int[] number) throws DocumentException {
// 创建一个有N列的表格
PdfPTable table = new PdfPTable(total);
table.setPaddingTop(20);
table.setSpacingAfter(20);
table.setTotalWidth(530); //设置列宽
table.setLockedWidth(true); //锁定列宽
PdfPCell cell;
//数组下标
int cos = 0;
for (int i = 0; i < data.size(); i++) { //遍历数据行 每个数据行都是一个list
Iterator<String> it = data.get(i).iterator();
int count = 0;
while (it.hasNext()) { //遍历每行数据,每个数据都是一个单元格
cell = new PdfPCell(new Phrase(it.next(), textFont));
cell.setMinimumHeight(17); //设置单元格高度
cell.setUseAscender(true); //设置可以居中
if (cos < rowspan.length && i == rowspan[cos] - 1 && count == colspan[cos] - 1) {
cell.setColspan(number[cos]);//跨单元格
cos++;
}
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //设置垂直居中
table.addCell(cell);
count++;
}
}
doc.add(table);
}
public static void TableColspanNo(int total, Font textFont, List<List<String>> data, Document doc, int[] rowspan, int[] colspan, int[] number) throws DocumentException {
// 创建一个有N列的表格
PdfPTable table = new PdfPTable(total);
//设置列宽
table.setTotalWidth(530);
//锁定列宽
table.setLockedWidth(true);
PdfPCell cell;
//数组下标
int cos = 0;
for (int i = 0; i < data.size(); i++) { //遍历数据行 每个数据行都是一个list
Iterator<String> it = data.get(i).iterator();
int count = 0;
while (it.hasNext()) { //遍历每行数据,每个数据都是一个单元格
cell = new PdfPCell(new Phrase(it.next(), textFont));
cell.setMinimumHeight(17); //设置单元格高度
cell.setUseAscender(true); //设置可以居中
if (cos < rowspan.length && i == rowspan[cos] - 1 && count == colspan[cos] - 1) {
cell.setColspan(number[cos]);//跨单元格
cos++;
}
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //设置垂直居中
table.addCell(cell);
count++;
}
}
doc.add(table);
}
}
GetData
static class GetData {
private final static Map<String, String> desensitizationData = new LinkedHashMap<>();
static {
desensitizationData.put("EntName", "深圳******有限公司");
desensitizationData.put("RegAddress", "深圳市**区******");
desensitizationData.put("SocialCreditCode", "9***************1");
desensitizationData.put("ESocialCreditCode", "9***************1");
desensitizationData.put("EntRegNo", "1*******0");
desensitizationData.put("Legal", "***");
desensitizationData.put("EntOrgCode", "1********0");
desensitizationData.put("ShareholderName", "***");
desensitizationData.put("FDDBRXM", "***");
desensitizationData.put("FDDBRSFZJHM", "440**************2");
desensitizationData.put("FDDBRGDDH", "0755-*******");
desensitizationData.put("FDDBRYDDH", "13********0");
desensitizationData.put("MemberName", "***");
desensitizationData.put("InvestName", "深圳******有限公司");
desensitizationData.put("ChangeItem", "***变更");
desensitizationData.put("ChangeBefore", "*****");
desensitizationData.put("ChangeAfter", "********");
desensitizationData.put("AccFundNo", "10*******3");
desensitizationData.put("SocialSecurityNo", "1******0");
desensitizationData.put("RestrictDesc", "******");
desensitizationData.put("PatentName", "******");
desensitizationData.put("PubNo", "******");
desensitizationData.put("WorkName", "******");
desensitizationData.put("RegNum", "******");
desensitizationData.put("TrademarkName", "******");
desensitizationData.put("RregCode", "******");
desensitizationData.put("LicenseNo", "******");
desensitizationData.put("CaseReason", "******");
desensitizationData.put("CaseNo", "******");
desensitizationData.put("CaseName", "******");
desensitizationData.put("PunishContent", "******");
desensitizationData.put("ViolationCaseNo", "*********");
desensitizationData.put("projectName", "*********");
desensitizationData.put("WebSite", "*********");
desensitizationData.put("Tel", "*********");
desensitizationData.put("Phone", "*********");
desensitizationData.put("IDNo", "*********");
desensitizationData.put("CaseCode", "*********");
}
public static String get(Map map, Compoent compoent, String key) {
List data = Optional.ofNullable((List) map.get(compoent.getValue())).orElse(new ArrayList<>());
IMap imap = new IMap();
if (data.size() > 0) {
if (data.get(0) instanceof JSONObject) {
((JSONObject) data.get(0)).forEach(imap::put);
}
}
return Optional.ofNullable(imap.get(key)).orElse("-");
}
public static String get(Map map, Compoent compoent, String key, boolean desensitization) {
List data = Optional.ofNullable((List) map.get(compoent.getValue())).orElse(new ArrayList<>());
IMap imap = new IMap();
if (data.size() > 0) {
if (data.get(0) instanceof JSONObject) {
if (desensitization) {
((JSONObject) data.get(0)).forEach((k, v) -> {
String s = String.valueOf(v);
imap.put(k, desensitizationData.getOrDefault(k, s));
});
} else {
((JSONObject) data.get(0)).forEach(imap::put);
}
}
}
return Optional.ofNullable(imap.get(key)).orElse("-");
}
public static List<List<String>> get(Map result, Compoent compoent, String... keys) {
List<List<String>> res = new ArrayList<>();
Optional.ofNullable(result.get(compoent.getValue())).ifPresent(v -> {
if (v instanceof ArrayList) {
((ArrayList) v).forEach(o -> {
List<String> data = new ArrayList<>();
JSONObject item = ((JSONObject) o);
for (String key : keys) {
data.add(StringUtils.isEmpty(item.getString(key)) ? "-" : item.getString(key));
}
res.add(data);
});
}
});
if (res.size() == 0) {
List<String> data = new ArrayList<>();
for (int i = 0; i < keys.length; i++) {
data.add("");
}
res.add(data);
}
return res;
}
public static List<List<String>> get(Boolean desensitization, Map result, Compoent compoent, String... keys) {
List<List<String>> res = new ArrayList<>();
Optional.ofNullable(result.get(compoent.getValue())).ifPresent(v -> {
if (v instanceof ArrayList) {
((ArrayList) v).forEach(o -> {
List<String> data = new ArrayList<>();
JSONObject item = ((JSONObject) o);
for (String key : keys) {
if (desensitization) {
data.add(StringUtils.isEmpty(item.getString(key)) ? "-" : desensitizationData.get(key) == null ? item.getString(key) : desensitizationData.get(key));
} else {
data.add(StringUtils.isEmpty(item.getString(key)) ? "-" : item.getString(key));
}
}
res.add(data);
});
}
});
if (res.size() == 0) {
List<String> data = new ArrayList<>();
for (int i = 0; i < keys.length; i++) {
data.add("");
}
res.add(data);
}
return res;
}
public static List<List<String>> get(Map result, Predicate<JSONObject> predicate, Compoent compoent, String... keys) {
List<List<String>> res = new ArrayList<>();
Optional.ofNullable(result.get(compoent.getValue())).ifPresent(v -> {
if (v instanceof ArrayList) {
((ArrayList) v).stream().filter(predicate).forEach(o -> {
List<String> data = new ArrayList<>();
JSONObject item = ((JSONObject) o);
for (String key : keys) {
data.add(StringUtils.isEmpty(item.getString(key)) ? "-" : item.getString(key));
}
if (data.size() == 0) {
List<String> row = new ArrayList<>();
for (int i = 0; i < keys.length; i++) {
row.add("");
}
data.addAll(row);
}
res.add(data);
});
}
});
return res;
}
public static List<Map> getListMap(Map result, Compoent compoent, String... keys) {
List<Map> data = new ArrayList<>();
Optional.ofNullable(result.get(compoent.getValue())).ifPresent(v -> {
if (v instanceof ArrayList) {
((ArrayList) v).forEach(o -> {
JSONObject item = ((JSONObject) o);
Map map = new LinkedHashMap(16);
for (String key : keys) {
map.put(key, StringUtils.isEmpty(item.getString(key)) ? "-" : item.getString(key));
}
data.add(map);
});
}
});
return data;
}
}
RowData
static class RowData {
public static List<String> add(String... cells) {
return Arrays.asList(cells);
}
public static List<String> add(String cells, List<String> datas) {
datas.add(0, cells);
return datas;
}
public static List<String> add(String cells, Map<String, String> data, Function<Map<String, String>, List<String>> func) {
List<String> res = func.apply(data);
res.add(0, cells);
return res;
}
public static List<List<String>> add(Map<String, List<Map>> data, Function<Map<String, List<Map>>, List<List<String>>> func) {
List<List<String>> res = func.apply(data);
return res;
}
}
TableDataUtil
static class TableDataUtil {
public List<List<String>> data = new ArrayList<>();
public TableDataUtil add(List<String> rowData) {
if (rowData != null && rowData.size() > 0) {
data.add(rowData);
}
return this;
}
public TableDataUtil addList(List<List<String>> rowData) {
data.addAll(rowData);
return this;
}
public List<List<String>> toList() {
return data;
}
public TableDataUtil add(Map<String, List<Map>> data, Function<Map<String, List<Map>>, List<List<String>>> res) {
this.data.addAll(res.apply(data));
return this;
}
}
ChartUtil
static class ChartUtil {
private static final Color[] BAR_COLORS = new Color[]{
new Color(79, 129, 189),
new Color(192, 80, 77),
new Color(155, 187, 89),
new Color(128, 100, 162),
new Color(75, 172, 198),
new Color(247, 150, 70),
new Color(119, 44, 42),
new Color(77, 59, 98),
new Color(182, 87, 8),
};
private static final Color[] LINE_COLORS = new Color[]{
new Color(90, 154, 213),
new Color(237, 123, 46),
new Color(155, 187, 89),
};
private static final Color[] PIE_COLORS = new Color[]{
new Color(79, 129, 189),
new Color(192, 80, 77),
new Color(155, 187, 89),
new Color(128, 100, 162),
new Color(75, 172, 198),
new Color(247, 150, 70),
new Color(119, 44, 42),
new Color(77, 59, 98),
new Color(182, 87, 8),
};
private static StandardChartTheme initChartTheme() {
StandardChartTheme currentTheme = new StandardChartTheme("JFree");
currentTheme.setLargeFont(new java.awt.Font("宋体", java.awt.Font.BOLD, 15));
currentTheme.setRegularFont(new java.awt.Font("宋体", java.awt.Font.PLAIN, 13));
currentTheme.setExtraLargeFont(new java.awt.Font("宋体", java.awt.Font.BOLD, 20));
currentTheme.setPlotBackgroundPaint(new Color(255, 255, 204, 0));
currentTheme.setPlotOutlinePaint(new Color(0, 0, 0, 0));
currentTheme.setRangeGridlinePaint(new Color(78, 74, 74));
return currentTheme;
}
/**
* 线图
*
* @param title 标题
* @param categoryAxisLabel 分类标签
* @param valueAxisLabel 数值标签
* @param dataset 数据集
* @return org.jfree.chart.JFreeChart
* @author Hou_fx
* @date 2021.8.4 10:39
*/
public static JFreeChart lineChart(String title, String categoryAxisLabel, String valueAxisLabel, DefaultCategoryDataset dataset) {
ChartFactory.setChartTheme(initChartTheme());
JFreeChart chart = ChartFactory.createLineChart(
title,
categoryAxisLabel,
valueAxisLabel,
dataset,
PlotOrientation.VERTICAL,
true,
true,
false
);
CategoryPlot plot = chart.getCategoryPlot();
LineAndShapeRenderer renderer = (LineAndShapeRenderer) plot.getRenderer();
renderer.setDefaultItemLabelsVisible(true);
renderer.setDefaultItemLabelGenerator(new StandardCategoryItemLabelGenerator());
for (int i = 0; i < dataset.getRowKeys().size(); i++) {
if (i > LINE_COLORS.length - 1) {
renderer.setSeriesPaint(i, new Color(RandomUtils.nextInt(110, 200), RandomUtils.nextInt(110, 200), RandomUtils.nextInt(110, 200)));
} else {
renderer.setSeriesPaint(i, LINE_COLORS[i]);
}
}
return chart;
}
public static JFreeChart lineChart(String title, String categoryAxisLabel, String valueAxisLabel, DefaultCategoryDataset dataset, CategoryLabelPositions position) {
ChartFactory.setChartTheme(initChartTheme());
JFreeChart chart = ChartFactory.createLineChart(
title,
categoryAxisLabel,
valueAxisLabel,
dataset,
PlotOrientation.VERTICAL,
true,
true,
false
);
CategoryPlot plot = chart.getCategoryPlot();
plot.getDomainAxis().setCategoryLabelPositions(position);
LineAndShapeRenderer renderer = (LineAndShapeRenderer) plot.getRenderer();
renderer.setDefaultItemLabelsVisible(true);
renderer.setDefaultItemLabelGenerator(new StandardCategoryItemLabelGenerator());
for (int i = 0; i < dataset.getRowKeys().size(); i++) {
if (i > LINE_COLORS.length - 1) {
renderer.setSeriesPaint(i, new Color(RandomUtils.nextInt(110, 200), RandomUtils.nextInt(110, 200), RandomUtils.nextInt(110, 200)));
} else {
renderer.setSeriesPaint(i, LINE_COLORS[i]);
}
}
return chart;
}
/**
* 柱状图
*
* @param title
* @param categoryAxisLabel
* @param valueAxisLabel
* @param dataset 数据集
* @return org.jfree.chart.JFreeChart
* @author Hou_fx
* @date 2021.8.4 14:03
*/
public static JFreeChart barChart(String title, String categoryAxisLabel, String valueAxisLabel, DefaultCategoryDataset dataset) {
ChartFactory.setChartTheme(initChartTheme());
JFreeChart chart = ChartFactory.createBarChart(
title,
categoryAxisLabel,
valueAxisLabel,
dataset,
PlotOrientation.VERTICAL,
true,
true,
false
);
CategoryPlot plot = chart.getCategoryPlot();
BarRenderer renderer = (BarRenderer) plot.getRenderer();
renderer.setBarPainter(new StandardBarPainter());
renderer.setDefaultItemLabelsVisible(true);
renderer.setDefaultItemLabelGenerator(new StandardCategoryItemLabelGenerator());
renderer.setItemMargin(0.0);
for (int i = 0; i < dataset.getRowKeys().size(); i++) {
if (i > BAR_COLORS.length - 1) {
renderer.setSeriesPaint(i, new Color(RandomUtils.nextInt(110, 200), RandomUtils.nextInt(110, 200), RandomUtils.nextInt(110, 200)));
} else {
renderer.setSeriesPaint(i, BAR_COLORS[i]);
}
}
return chart;
}
public static JFreeChart barChart2(String title, String categoryAxisLabel, String valueAxisLabel, DefaultCategoryDataset dataset, DefaultCategoryDataset dataset2, String format2) {
ChartFactory.setChartTheme(initChartTheme());
JFreeChart chart = ChartFactory.createBarChart(
title,
categoryAxisLabel,
valueAxisLabel,
dataset,
PlotOrientation.VERTICAL,
true,
true,
false
);
CategoryPlot plot = chart.getCategoryPlot();
NumberAxis axis = new NumberAxis();
axis.setNumberFormatOverride(new DecimalFormat("#,##%"));
plot.setRangeAxis(1, axis);
plot.setRangeAxisLocation(1, AxisLocation.BOTTOM_OR_RIGHT);
plot.setDataset(1, dataset2);
plot.mapDatasetToRangeAxis(1, 1);
BarRenderer renderer2 = new BarRenderer();
renderer2.setSeriesPaint(0, new Color(238, 8, 8, 0));
renderer2.setDefaultItemLabelsVisible(true);
renderer2.setDefaultItemLabelGenerator(new StandardCategoryItemLabelGenerator(format2, NumberFormat.getInstance()));
ItemLabelPosition position1 = new ItemLabelPosition(ItemLabelAnchor.INSIDE12, TextAnchor.TOP_RIGHT);
renderer2.setDefaultPositiveItemLabelPosition(position1);
plot.setRenderer(1, renderer2);
BarRenderer renderer = (BarRenderer) plot.getRenderer();
renderer.setBarPainter(new StandardBarPainter());
renderer.setDefaultItemLabelsVisible(true);
renderer.setDefaultItemLabelGenerator(new StandardCategoryItemLabelGenerator());
renderer.setItemMargin(0.0);
for (int i = 0; i < dataset.getRowKeys().size(); i++) {
if (i > BAR_COLORS.length - 1) {
renderer.setSeriesPaint(i, new Color(RandomUtils.nextInt(110, 200), RandomUtils.nextInt(110, 200), RandomUtils.nextInt(110, 200)));
} else {
renderer.setSeriesPaint(i, BAR_COLORS[i]);
}
}
return chart;
}
public static JFreeChart barChart(String title, String categoryAxisLabel, String valueAxisLabel, DefaultCategoryDataset dataset, String format) {
ChartFactory.setChartTheme(initChartTheme());
JFreeChart chart = ChartFactory.createBarChart(
title,
categoryAxisLabel,
valueAxisLabel,
dataset,
PlotOrientation.VERTICAL,
true,
true,
false
);
CategoryPlot plot = chart.getCategoryPlot();
BarRenderer renderer = (BarRenderer) plot.getRenderer();
renderer.setBarPainter(new StandardBarPainter());
renderer.setDefaultItemLabelsVisible(true);
renderer.setDefaultItemLabelGenerator(new StandardCategoryItemLabelGenerator(format, NumberFormat.getInstance()));
renderer.setItemMargin(0.0);
for (int i = 0; i < dataset.getRowKeys().size(); i++) {
if (i > BAR_COLORS.length - 1) {
renderer.setSeriesPaint(i, new Color(RandomUtils.nextInt(110, 200), RandomUtils.nextInt(110, 200), RandomUtils.nextInt(110, 200)));
} else {
renderer.setSeriesPaint(i, BAR_COLORS[i]);
}
}
return chart;
}
/**
* 饼图
*
* @param title
* @param dataset
* @return org.jfree.chart.JFreeChart
* @author Hou_fx
* @date 2021.8.4 14:04
*/
public static JFreeChart pieChart(String title, DefaultPieDataset<String> dataset) {
ChartFactory.setChartTheme(initChartTheme());
JFreeChart chart = ChartFactory.createPieChart(
title,
dataset,
true,
true,
false
);
PiePlot plot = (PiePlot) chart.getPlot();
for (int i = 0; i < dataset.getKeys().size(); i++) {
if (i > PIE_COLORS.length - 1) {
plot.setSectionPaint(dataset.getKey(i), new Color(RandomUtils.nextInt(110, 200), RandomUtils.nextInt(110, 200), RandomUtils.nextInt(110, 200)));
} else {
plot.setSectionPaint(dataset.getKey(i), PIE_COLORS[i]);
}
}
plot.setDefaultSectionOutlinePaint(new Color(255, 255, 255));
plot.setDefaultSectionOutlineStroke(new BasicStroke(3));
//plot.setLabelLinkPaint(new Color(255, 255, 255, 0));
plot.setLabelBackgroundPaint(new Color(255, 255, 255, 0));
plot.setLabelOutlinePaint(new Color(255, 255, 255, 0));
plot.setLabelShadowPaint(new Color(255, 255, 255, 0));
plot.setShadowPaint(new Color(255, 255, 255, 0));
//plot.setLabelGenerator(new StandardPieSectionLabelGenerator(("{0}{2}"), NumberFormat.getNumberInstance(), new DecimalFormat("0.00%")));
plot.setLabelGenerator(new StandardPieSectionLabelGenerator(("{2}"), NumberFormat.getNumberInstance(), new DecimalFormat("0.00%")));
return chart;
}
}