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));
    }
}
相关推荐
小白今天也很酷4 小时前
Python与MCU通信:串口数据采集及CSV/Excel存储方法
python·单片机·excel
xlxxy_8 小时前
ABAP数据库表的增改查
开发语言·前端·数据库·sql·oracle·excel
程序猿多布10 小时前
Unity Excel导表工具转Lua文件
unity·excel
The god of big data14 小时前
Excel核心函数VLOOKUP全解析:从入门到精通
excel
专注VB编程开发20年1 天前
除了 EasyXLS,加载和显示.xlsx 格式的excel表格,并支持单元格背景色、边框线颜色和粗细等格式化特性
c++·windows·excel·mfc·xlsx
诸神缄默不语1 天前
Excel如何给单元格填色,以及如何用Python 3实现单元格填色
开发语言·python·excel·openpyxl·patternfill
程序员小续1 天前
Excel 表格和 Node.js 实现数据转换工具
前端·javascript·react.js·前端框架·vue·excel·reactjs
jiemidashi2 天前
WPS 中 Excel 密码取消方法大解密
经验分享·excel·wps
赵域Phoenix2 天前
挑选出行数足够的excel文件
开发语言·python·excel
oh,huoyuyan2 天前
火语言RPA--Excel读取内容
excel·rpa