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));
    }
}
相关推荐
KeThink1 小时前
国民经济行业分类 GB/T 4754—2017 (PDF和exce版本)
pdf·excel
_oP_i1 小时前
Excel 的多线程特性
excel
V1ncent Chen4 小时前
Excel基础:数据查看
excel
谁他个天昏地暗14 小时前
Java 实现 Excel 文件对比与数据填充
java·开发语言·excel
梦想blog14 小时前
Spring Boot + Easy Excel 自定义复杂样式导入导出
excel
UrbanJazzerati1 天前
使用Excel制作多类别占比分析字母饼图
excel
The Future is mine1 天前
Python实现文件夹中文件名与Excel中存在的文件名进行对比,并进行删除操作
excel
Tomorrow'sThinker2 天前
[特殊字符] Excel 读取收件人 + Outlook 批量发送带附件邮件 —— Python 自动化实战
python·excel·outlook
盛夏绽放2 天前
ExcelJS 完全指南:专业级Excel导出解决方案
excel·有问必答
bing_1582 天前
Excel 如何进行多条件查找或求和?
excel