pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports</artifactId>
<version>6.6.0</version>
</dependency>
<dependency>
<groupId>com.kevin</groupId>
<artifactId>myfont</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
</dependencies>
创建excel表格
public class CreateExcel {
public static void getExcel(String filepath, List<A> listA, List<B> listB) {
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("table");// 创建table工作薄
Object[][] datas = new Object[listA.size()+1][7];
datas[0][0] = "A网站:";
datas[0][1] = "访问量";
datas[0][2] = "年份";
datas[0][3] = " |";
datas[0][4] = "B网站:";
datas[0][5] = "访问量";
datas[0][6] = "年份";
for(int i = 1; i < listA.size()+1;i++) {
datas[i][0] = "";
datas[i][1] = listA.get(i-1).getNum();
datas[i][2] = listA.get(i-1).getYear();
datas[i][3] = " |";
datas[i][4] = "";
datas[i][5] = listB.get(i-1).getNum();
datas[i][6] = listB.get(i-1).getYear();
}
HSSFRow row;
HSSFCell cell;
for (int i = 0; i < datas.length; i++) {
row = sheet.createRow(i);// 创建表格行
for (int j = 0; j < datas[i].length; j++) {
cell = row.createCell(j);// 根据表格行创建单元格
cell.setCellValue(String.valueOf(datas[i][j]));
}
}
/*CellRangeAddress region = new CellRangeAddress(0,listA.size()-1,0,0);
CellRangeAddress region1 = new CellRangeAddress(0,listB.size()-1,4,4);
sheet.addMergedRegion(region);
sheet.addMergedRegion(region1);*/
try {
wb.write(new FileOutputStream(filepath));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
创建折线图
public class CreateJFreeChartXYLine {
/**
* 创建JFreeChart LineXY Chart(折线图)
*/
public static void CreatePNG(String fileName, List<A> listA, List<B> listB) {
XYDataset dataset = createDataset(listA,listB);
JFreeChart chart = ChartFactory.createTimeSeriesChart("两个网站访问量统计", "Year","Price Per Unit", dataset, true, true, false);
// some additional chart customisation here...
XYPlot plot = chart.getXYPlot();
XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) plot.getRenderer();
renderer.setShapesVisible(true);
DateAxis axis = (DateAxis) plot.getDomainAxis();
axis.setDateFormatOverride(new SimpleDateFormat("YYYY"));
File file = new File(fileName);
try {
ChartUtilities.saveChartAsPNG(file, chart, 600, 400);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 创建XYDataset对象
*/
private static XYDataset createDataset(List<A> listA,List<B> listB) {
// A网站的访问量统计
TimeSeries timeSeries=new TimeSeries("A网站访问量统计", Month.class);
for (A a : listA) {
timeSeries.add(new Month(1,a.getYear()),a.getNum());
}
// B网站的访问量统计
//如果有更多的就继续添加就行了
TimeSeries timeSeries2=new TimeSeries("B网站访问量统计", Month.class);
for (B b : listB) {
timeSeries2.add(new Month(1,b.getYear()),b.getNum());
}
TimeSeriesCollection lineDataset=new TimeSeriesCollection();
lineDataset.addSeries(timeSeries);
lineDataset.addSeries(timeSeries2);
return lineDataset;
}
}
创建柱状图
public class CreateJFreeZhu {
public static void getZhu(String fileName, List<A> listA, List<B> listB) {
// TODO Auto-generated method stub
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
// 添加数据
for(int i = 0;i < listA.size(); i++) {
dataset.addValue(listA.get(i).getNum(), "A网站访问量统计", listA.get(i).getYear()+"");
dataset.addValue(listB.get(i).getNum(), "B网站访问量统计", listB.get(i).getYear()+"");
}
JFreeChart chart = ChartFactory.createBarChart3D("两个网站访问量统计", "Year", // X轴的标签
"访问量", // Y轴的标签
dataset, // 图标显示的数据集合
PlotOrientation.VERTICAL, // 图像的显示形式(水平或者垂直)
true, // 是否显示子标题
true, // 是否生成提示的标签
true); // 是否生成URL链接
// 在D盘目录下生成图片
File file = new File(fileName);
try {
ChartUtilities.saveChartAsPNG(file, chart, 600, 400);
} catch (IOException e) {
e.printStackTrace();
}
}
}
将Excel转化为图片
public class ExcelToPNG {
public static void ConvertToImage(String filepath,String outpath) {
if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生
return;
}
Workbook book = null;
try {
book = new Workbook(filepath);
Worksheet sheet = book.getWorksheets().get(0);
ImageOrPrintOptions imgOptions = new ImageOrPrintOptions();
imgOptions.setImageFormat(ImageFormat.getPng());
imgOptions.setCellAutoFit(true);
imgOptions.setOnePagePerSheet(true);
SheetRender render = new SheetRender(sheet, imgOptions);
render.toImage(0, outpath);
} catch (Exception e) {
e.printStackTrace();
}
}
public static boolean getLicense() {
boolean result = false;
try {
InputStream is = ExcelToPNG.class.getClassLoader().getResourceAsStream("license.xml"); // license.xml应放在..\WebRoot\WEB-INF\classes路径下
License aposeLic = new License();
aposeLic.setLicense(is);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/*public static void excel2pdf(String Address) {
if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生
return;
}
try {
File pdfFile = new File("F:/mm.pdf");// 输出路径
Workbook wb = new Workbook("F:/abc.xls");// 原始excel路径
FileOutputStream fileOS = new FileOutputStream(pdfFile);
wb.save(fileOS, SaveFormat.PDF);
fileOS.close();
} catch (Exception e) {
e.printStackTrace();
}
}*/
}
创建PDF文件,放入一张图片
public class PrintToPdfUtil {
/**
*
* @param imageFolderPath
* 图片文件夹地址
* @param pdfPath
* PDF文件保存地址
*
*/
public static File[] toPdf(String imageFolderPath, String pdfPath) {
try {
// 图片文件夹地址
// 图片地址
String imagePath = null;
// PDF文件保存地址
// 输入流
FileOutputStream fos = new FileOutputStream(pdfPath);
// 创建文档
Document doc = new Document(null, 0, 0, 0, 0);
doc.setPageSize(new Rectangle(2000, 1400));
// 写入PDF文档
PdfWriter.getInstance(doc, fos);
// 读取图片流
BufferedImage img = null;
// 实例化图片
Image image = null;
// 获取图片文件夹对象
File file = new File(imageFolderPath);
File[] files = file.listFiles();
// 循环获取图片文件夹内的图片
if (files[0].getName().endsWith(".png")
|| files[0].getName().endsWith(".jpg")
|| files[0].getName().endsWith(".gif")
|| files[0].getName().endsWith(".jpeg")
|| files[0].getName().endsWith(".tif")) {
imagePath = imageFolderPath + "/" + files[0].getName();
// 读取图片流
img = ImageIO.read(new File(imagePath));
// 根据图片大小设置文档大小
// 实例化图片
image = Image.getInstance(imagePath);
// 添加图片到文档
doc.open();
doc.add(image);
}
// 关闭文档
doc.close();
return files;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
将其他图片分别加入到PDF中
public class AddPNG {
public static void addPNGToPDF(String pdf1,String pdf2,String filename,File[] files) {
try {
PdfReader reader = new PdfReader(pdf1);//指定将和 图片拼接的 PDF
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(pdf2));//生成的PDF 路径
PdfContentByte overContent = stamper.getOverContent(1);
int num = 2;
for(int i = 1; i < files.length; i++) {
if (files[i].getName().endsWith(".png")
|| files[i].getName().endsWith(".jpg")
|| files[i].getName().endsWith(".gif")
|| files[i].getName().endsWith(".jpeg")
|| files[i].getName().endsWith(".tif")) {
Image image = Image.getInstance(filename + files[i].getName());
if(i % 3 == 0) {
num--;
if(num == 1) {
image.setAbsolutePosition(0,num * 400 + 100);//左边距、底边距
}else {
image.setAbsolutePosition(0,0);//左边距、底边距
}
}else {
if(num == 2) {
image.setAbsolutePosition(700 * (i % 3),num * 400 + 200);//左边距、底边距
}else if(num == 1) {
image.setAbsolutePosition(700 * (i % 3),num * 400 + 100);//左边距、底边距
}else {
image.setAbsolutePosition(700 * (i % 3),0);//左边距、底边距
}
}
//添加图片
//图片名称
overContent.addImage(image);
overContent.stroke();
}
}
stamper.close();
reader.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
清空中间文件及文件夹
public class ClearFiles {
public static boolean delAllFile(String path) {
boolean flag = false;
File file = new File(path);
if (!file.exists()) {
return flag;
}
if (!file.isDirectory()) {
return flag;
}
String[] tempList = file.list();
File temp = null;
for (int i = 0; i < tempList.length; i++) {
if (path.endsWith(File.separator)) {
temp = new File(path + tempList[i]);
} else {
temp = new File(path + File.separator + tempList[i]);
}
if (temp.isFile()) {
temp.delete();
}
if (temp.isDirectory()) {
delAllFile(path + "/" + tempList[i]);//先删除文件夹里面的文件
flag = true;
}
}
return flag;
}
}
最终生成的文件效果
![](https://i-blog.csdnimg.cn/blog_migrate/06e079328183e283fcfa5004b299795e.jpeg)
如有错误之处,请给位大佬指正