项目有个需求是生成上图的表格图表,本来excel很容易生成上边的表格图,但是java poi不支持在服务器端把excel表格导出成图片,在没有找到合适的工具库下,用java 2d实现同样图表。
这个表格图分成标题、表头、表中、表尾4个部分,
背景填充用:graphics.fillRect()
画线条用:graphics.drawLine()
画文字用:graphics.drawString()
主要用上边三个java 2d方法实现,剩下的就是各种坐标位置的计算。
实现代码:
package com.penngo.test;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Arrays;
import java.util.List;
public class ExcelChart {
private Font titleFont = new Font("宋体",Font.BOLD,20);
private Font headFont = new Font("宋体",Font.BOLD,16);
private Font rowFont = new Font("宋体",Font.PLAIN,14);
private Font bottomFont = new Font("宋体",Font.PLAIN,14);
private Color titleBackgroup = new Color(237, 125, 49); // 标题背景色
private Color headBackgroup = new Color(252, 228, 214); // 表头背景色
private Color lineColor = new Color(237, 125,49); // 线条颜色
private int titleMargin = 8;
private int headMargin = 8;
private int rowMargin = 5;
private int bottomMargin = 5;
private int width;
private int height;
private int widthMargin = 10; // x横轴边距
private int heightMargin = 10; // y轴边框
/**
* 将图片保存到指定位置
* @param image 缓冲文件类
* @param fileLocation 文件位置
*/
public void createImage(BufferedImage image, File fileLocation) {
try {
ImageIO.write(image, "png", fileLocation);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 字符串总宽度
* @param g
* @param str
* @return
*/
private int getStringWidth(Graphics g,String str) {
char[] strcha=str.toCharArray();
int strWidth = g.getFontMetrics().charsWidth(strcha, 0, str.length());
return strWidth;
}
//字符高度
private int getStringHeight(Graphics g) {
int height = g.getFontMetrics().getHeight();
return height;
}
private int calculateImageHeight(int rowCount){
BufferedImage image = new BufferedImage(100, 100,BufferedImage.TYPE_INT_RGB);
Graphics graphics = image.getGraphics();
graphics.setFont(titleFont);
int titleRowHeight = getStringHeight(graphics) + titleMargin *