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

maven依赖

html 复制代码
        <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>

代码

java 复制代码
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));
    }
}
相关推荐
大G哥17 小时前
pytest自动化测试数据驱动yaml/excel/csv/json
json·excel·pytest
小奥超人17 小时前
Excel粘贴复制不完整的原因以及解决方法
windows·经验分享·microsoft·excel·办公技巧
code04号18 小时前
python脚本:批量提取excel数据
开发语言·python·excel
m0_7482552620 小时前
vue3导入excel并解析excel数据渲染到表格中,纯前端实现。
前端·excel
左漫在成长21 小时前
王佩丰24节Excel学习笔记——第十九讲:Indirect函数
笔记·学习·excel
Just_Paranoid21 小时前
解析 Java 项目生成常量、变量和函数 Excel 文档
java·python·正则表达式·excel·javadoc
H4_xy1 天前
Excel中match()函数
excel
左漫在成长1 天前
王佩丰24节Excel学习笔记——第十八讲:Lookup和数组
笔记·学习·excel
扶尔魔ocy1 天前
【QT开发自制小工具】PDF/图片转excel---调用百度OCR API接口
qt·pdf·ocr·excel
今天不学习明天变拉吉1 天前
大批量数据导入接口的优化
java·excel