Excel(11) : 生成xlsx添加图片

2024-01-08 21:29:59

maven依赖


        <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>4.1.2</version>
        </dependency>

代码


import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLEncoder;

public class ExcelImageUtil {

    public static void main(String[] args) throws Exception {
        /// 创建Xlsx
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("测试Excel");
        Row headerRow = sheet.createRow(0);
        headerRow.createCell(0).setCellValue("第一列");
        headerRow.createCell(1).setCellValue("第二列");
        headerRow.createCell(2).setCellValue("第三列");
        int rowIndex = 1;
        for (int i = 0; i < 3; i++) {
            Row dataRow = sheet.createRow(rowIndex);
            dataRow.createCell(0).setCellValue(rowIndex + "_" + 0);
            dataRow.createCell(1).setCellValue(rowIndex + "_" + 1);
            rowIndex++;
        }

        /// 添加图片
        addImg(workbook, sheet, 2, 1, getBaopsByFile("E:\\t1.jpg"));
        addImg(workbook, sheet, 2, 1, getBaopsByFile("E:\\t2.jpg"));
        addImg(workbook, sheet, 2, 1, getBaopsByFile("E:\\t3.jpg"));

        /// 生成本地文件
        FileOutputStream fileOut = new FileOutputStream("E:\\t2.xlsx");
        workbook.write(fileOut);

        /// TODO 可选, HTTP接口浏览器直接下载文件
        HttpServletResponse response = null;
        // 设置content—type
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset:utf-8");
        // 设置标题
        String fileName = URLEncoder.encode("t2", "UTF-8");
        //Content-disposition是MIME协议的扩展,MIME协议指示MIME用户代理如何显示附加的文件。
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
        ServletOutputStream outputStream = response.getOutputStream();
        //将Writer刷新到OutPut
        workbook.write(outputStream);
        outputStream.close();
    }


    public static ByteArrayOutputStream getBaopsByFile(String filePath) throws Exception {
        FileInputStream fis = new FileInputStream(filePath);
        ByteArrayOutputStream baops = new ByteArrayOutputStream(fis.available());
        byte[] bytes = new byte[fis.available()];
        int temp;
        while ((temp = fis.read(bytes)) != -1) {
            baops.write(bytes, 0, temp);
        }
        fis.close();
        baops.close();
        return baops;
    }

    public static ByteArrayOutputStream getBaopsByUrl(String fileUrl) throws Exception {
        InputStream inputStream = new URL(fileUrl).openStream();
        ByteArrayOutputStream baops = new ByteArrayOutputStream(inputStream.available());
        byte[] bytes = new byte[inputStream.available()];
        int temp;
        while ((temp = inputStream.read(bytes)) != -1) {
            baops.write(bytes, 0, temp);
        }
        inputStream.close();
        baops.close();
        return baops;
    }


    public static void addImg(Workbook workbook, Sheet sheet, int cellIndex, int rowIndex, ByteArrayOutputStream byteArrayOutputStream) {
        Drawing<?> drawing = sheet.createDrawingPatriarch();
        sheet.setColumnWidth(cellIndex, 120 * 256);
        sheet.getRow(rowIndex).setHeight((short) (70 * 60));

        CreationHelper helper = workbook.getCreationHelper();
        ClientAnchor anchor = helper.createClientAnchor();
        anchor.setCol1(cellIndex);
        anchor.setRow1(rowIndex);
        anchor.setCol2(cellIndex);
        anchor.setRow2(rowIndex);

        Picture picture = drawing.createPicture(anchor, workbook.addPicture(byteArrayOutputStream.toByteArray(), HSSFWorkbook.PICTURE_TYPE_JPEG));

        picture.resize(0.7);
        sheet.setColumnWidth(anchor.getCol1(), 30 * 256);
        sheet.getRow(rowIndex).setHeight((short) (30 * 60));
    }
}

文章来源:https://blog.csdn.net/Lxinccode/article/details/135413602
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。