ApachePOIExcel生成:多张图纸上不同的图像大小

ergxz8rk  于 2021-06-29  发布在  Java
关注(0)|答案(0)|浏览(213)

我正在编写一段代码,生成包含两张工作表的excel(*.xlsx)工作簿。在这两张图片上,我将在左上角放置相同的logo.png图片(151x90px)。第一页和第二页的第一列宽度不同。第一张更宽。
excel文件生成后,第一页上的图片看起来很好,但第二页上的图片更宽(110%)
我怎样才能使照片在两张纸上都有原来的尺寸?
我正在使用ApachePOI3.17
下面是我的示例代码:

package mchodun.excel;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.ClientAnchor;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.Drawing;
import org.apache.poi.ss.usermodel.Picture;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.junit.Test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Paths;

public class ExcelFileTest {

    @Test
    public void testImage() throws IOException {
        Workbook workbook = new SXSSFWorkbook(100);
        InputStream is = new FileInputStream(
                "/Users/mchodun/Desktop/logo.png");
        byte[] pictureBytes = IOUtils.toByteArray(is);
        createSheet(workbook, pictureBytes, true);
        createSheet(workbook, pictureBytes, false);

        final File fileDest = Paths.get("/Users/mchodun/Desktop", "test.xlsx")
                .toFile();
        // gets output stream
        final OutputStream out = new FileOutputStream(fileDest);
        workbook.write(out);
        out.flush();
        out.close();
    }

    private void createSheet(Workbook workbook, byte[] pictureBytes,
                             boolean changeColumnWidth) {
        final int pictureIdx = workbook.addPicture(pictureBytes,
                Workbook.PICTURE_TYPE_PNG);
        Sheet sheet = workbook.createSheet();
        if (changeColumnWidth) {
            sheet.setColumnWidth(0, 16000);
        }
        final CreationHelper helper = workbook.getCreationHelper();
        final Drawing drawing = sheet.createDrawingPatriarch();
        final ClientAnchor anchor = helper.createClientAnchor();

        // create an anchor with upper left cell and bottom right cell
        anchor.setCol1(0);
        anchor.setRow1(0);
        anchor.setCol2(0);
        anchor.setRow2(0);

        Picture picture = drawing.createPicture(anchor, pictureIdx);
        Row row0 = sheet.createRow(0);
        row0.setHeight((short) (picture.getImageDimension().getHeight() * 15));

        Row row1 = sheet.createRow(1);
        Cell cell10 = row1.createCell(0);
        cell10.setCellValue("Value");

        picture.resize();
    }

}

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题