一、引入依赖
<!-- Apache POI -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version> <!-- 使用最新版本 -->
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.0.0</version>
</dependency>
二、创建一个ExcelToImage文件
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.Color;
import java.awt.Font;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class ExcelToImage {
public static void main(String[] args) throws IOException {
String excelFilePath = "E:\\test\\11\\1.xls";
String imageFilePath = "E:\\test\\11\\1.png";
convertExcelToImage(excelFilePath, imageFilePath);
}
public static void convertExcelToImage(String excelFilePath, String imageFilePath) throws IOException {
FileInputStream fis = new FileInputStream(new File(excelFilePath));
Workbook workbook;
if (excelFilePath.endsWith(".xls")) {
workbook = new HSSFWorkbook(fis); // For Excel 97-2003 (.xls) format
} else if (excelFilePath.endsWith(".xlsx")) {
workbook = new XSSFWorkbook(fis); // For Excel 2007 and later (.xlsx) format
} else {
throw new IllegalArgumentException("Unsupported file type");
}
Sheet sheet = workbook.getSheetAt(0);
int rowCount = sheet.getPhysicalNumberOfRows();
int colCount = sheet.getRow(0).getPhysicalNumberOfCells();
BufferedImage image = new BufferedImage(896, 424, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = image.createGraphics();
for (int i = 0; i < rowCount; i++) {
Row row = sheet.getRow(i);
for (int j = 0; j < colCount; j++) {
if(i==0){
graphics.setFont(new Font("宋体", Font.PLAIN, 16));
}else {
graphics.setFont(new Font("宋体", Font.PLAIN, 12));
}
Cell cell = row.getCell(j);
if (cell != null) {
if(j==0&&i==0){
graphics.setColor(new Color(20,91,133)); // 设置背景颜色
}
if((j==0&&i!=0)||(j!=0&&i==0)){
graphics.setColor(new Color(48,119,163)); // 设置背景颜色
}
if(j!=0&&i!=0){
graphics.setColor(new Color(89,142,176)); // 设置背景颜色
}
graphics.fillRect(j*150, i*47, 896, 424);
graphics.setColor(Color.WHITE); // 设置边框颜色
graphics.drawRect(j*150, i*47, 896, 424);
String cellValue = getCellValueAsString(cell);
graphics.drawString(cellValue, j * 150+10, i * 45+30);
}
}
}
graphics.dispose();
ImageIO.write(image, "png", new File(imageFilePath));
workbook.close();
fis.close();
}
private static String getCellValueAsString(Cell cell) {
String cellValue = "";
if (cell != null) {
switch (cell.getCellType()) {
case STRING:
cellValue = cell.getStringCellValue();
break;
case NUMERIC:
cellValue = String.valueOf(cell.getNumericCellValue());
break;
case BOOLEAN:
cellValue = String.valueOf(cell.getBooleanCellValue());
break;
case FORMULA:
cellValue = cell.getCellFormula();
break;
default:
cellValue = "";
}
}
return cellValue;
}
}
三、生成效果
excel
生成效果