Excel转图片

2018-04-06  本文已影响64人  Sanisy
  1. 之前在一个项目中,客户需要将生成的Excel文件进一步生成图片。在google上找到了一个博客:
    ExcelToImage
    核心代码如下:
public class ExcelToImageConverter {

    public static String generateImages(final String excelPath, String saveDir) {
        long currentTimes = System.currentTimeMillis();

        String imageFilePath = null;
        if (saveDir.lastIndexOf("/") != saveDir.length() - 1) {
            saveDir += "/";
        }

        try {
            Workbook workbook = new Workbook(excelPath);
            CellsHelper.setFontDir(fontDir);
            List<Worksheet> worksheets = getAllWorksheets(workbook);
            if (worksheets != null && worksheets.size() > 0) {
                for (Worksheet worksheet : worksheets) {
                    Worksheet worksheet = worksheets.get(0);
                    if (worksheet.getCells().getCount() > 0 || worksheet.getCharts().getCount() > 0 || worksheet.getPictures().getCount() > 0) {
                        imageFilePath = saveDir + RandomStringUtils.randomAlphanumeric(30) + ".jpeg";
                        SheetRender sr = new SheetRender(worksheet, getImageOrPrintOptions());
                        sr.toImage(0, imageFilePath);
                        return imageFilePath;
                    }
              }
            }
        } catch (Exception e) {
            log.error("excel转图片失败,excelPath={}", excelPath, e);
        }

        long endTimes = System.currentTimeMillis();
        System.out.println(endTimes - currentTimes);

        return imageFilePath;
    }

    /**
     * Returns all worksheets present in given workbook.
     *
     * @param workbook
     * @return all worksheets present in given workbook.
     */
    private static List<Worksheet> getAllWorksheets(final Workbook workbook) {
        List<Worksheet> worksheets = new ArrayList<Worksheet>();
        WorksheetCollection worksheetCollection = workbook.getWorksheets();
        for (int i = 0; i < worksheetCollection.getCount(); i++) {
            worksheets.add(worksheetCollection.get(i));
        }
        return worksheets;
    }

    /**
     * Returns ImageOrPrintOptions for png images
     *
     * @return
     */
    private static ImageOrPrintOptions getImageOrPrintOptions() {
        ImageOrPrintOptions imgOptions = new ImageOrPrintOptions();
        imgOptions.setImageFormat(ImageFormat.getJpeg());
        imgOptions.setOnePagePerSheet(true);
        return imgOptions;
    }
}

它用到的框架是aspose.cells,如果Excel中存在中文字符,而你部署的Linux服务器没有中文字体,那么会显示中文乱码。解决办法CellsHelper.setFontDir(fontDir);,同时把你的中文字体放到服务器的fontDir路径下。获取中文字体办法:在Windows系统下进入路径C:\Windows\Fonts

  1. Excel转成的图片的表头含有aspose这个框架的开源协议,解决办法:完成Excel转图片的操作后,对图片进行裁剪,将开源协议部分裁去。裁剪图片
上一篇 下一篇

猜你喜欢

热点阅读