TimeUtil是自定义时间函数可以自己实现。 Excel2Img 是当前类
package service;
import com.aspose.cells.*;
import utils.TimeUtil;
/**
* Convert Excel Sheet Data To Image
* @author yangxin_ryan
*/
public class Excel2Img {
private void convertToImage(String sourcePath, int sheetId, String startPoint, String endPoint) {
try {
TimeUtil timeUtil = new TimeUtil();
//获取文件名称
String picName = sourcePath.split("/")[3].split("\\.")[0];
System.out.println("picName: " + picName);
//文件保存位置
String resultPath = "/home/webserver/report_image_data/" + timeUtil.getDate() + "/" +
picName + ".jpeg";
System.out.println("resultPath: " + resultPath);
Workbook workbook = new Workbook(sourcePath);
Worksheet worksheet = workbook.getWorksheets().get(sheetId);
String area = startPoint + ":" + endPoint;
System.out.println("area: " + area);
// set the startPoint and endPoint
worksheet.getPageSetup().setPrintArea(area);
worksheet.getPageSetup().setLeftMargin(1);
worksheet.getPageSetup().setRightMargin(1);
worksheet.getPageSetup().setTopMargin(1);
worksheet.getPageSetup().setBottomMargin(1);
ImageOrPrintOptions options = new ImageOrPrintOptions();
options.setOnePagePerSheet(true);
options.setImageFormat(ImageFormat.getJpeg());
// set the fonts
CellsHelper.setFontDir("/usr/share/fonts/chinese/Fonts");
SheetRender sheetRender = new SheetRender(worksheet, options);
sheetRender.toImage(sheetId, resultPath);
System.out.println("Finish Convert Job");
} catch (Exception error) {
error.printStackTrace();
}
}
public static void main(String[] args) {
//文件所在位置
String sourcePath = "/xxx/xxxx.xlsx";
//页
int sheetId = 0;
//开始位置
String startPoint = "A1";
//结束位置
String endPoint = "O96";
Excel2Img excel2Img = new Excel2Img();
excel2Img.convertToImage(sourcePath, sheetId, startPoint, endPoint);
}
}
pom
<dependency>
<groupId>com.aspose</groupId>
<artifactId>aspose-cells</artifactId>
<version>19.3</version>
</dependency>