Java导出图片到excel

package org.jeecg.modules.tb.client;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.ss.util.*;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;


public class ExcelExportWithImage {
    public static void main(String[] args) {
        try (Workbook workbook = new XSSFWorkbook()) {
            Sheet sheet = workbook.createSheet("Data");
            // 设置表头
            Row headerRow = sheet.createRow(0);
            // 表头内容
            String[] headers = {"所属单位", "姓名", "身份证号", "违规项", "违规时间", "人脸照片", "抓拍照片"};
            setHeaders(headerRow, headers);
            //数据源
            List<Employee> employees = new ArrayList<>();
            employees.add(new Employee("Dept A", "John", "http://xxx/xxx/5181.jpg", "http://xxx/xxx/5281.jpg", "41282919980819", "2024-03-27 17:14:20", 15));
            employees.add(new Employee("Dept A", "Alice", "http://xxx/xxx/1181.jpg", "http://xxx/xxx/5191.jpg", "41282919980820", "2024-03-27 18:14:20", 16));
            employees.add(new Employee("Dept B", "Bob", "http://xxx/xxx/5381.jpg", "http://xxx/xxx/5111.jpg", "41282919980821", "2024-03-27 19:14:20", 15));
            // Insert data into Excel
            int rowIndex = 1;
            for (Employee employee : employees) {
                Row row = sheet.createRow(rowIndex);
                row.setHeightInPoints(70);
                sheet.setColumnWidth(0, 5500);
                sheet.setColumnWidth(2, 4000);
                sheet.setColumnWidth(3, 4000);
                sheet.setColumnWidth(4, 5000);
                sheet.setColumnWidth(5, 4500);
                sheet.setColumnWidth(6, 4500);

                // 填充数据
                //参建单位
                Cell deptCell = row.createCell(0);
                deptCell.setCellValue(employee.getDeptName());
                //姓名
                Cell nameCell = row.createCell(1);
                nameCell.setCellValue(employee.getName());
                //身份证号
                Cell idCardCell = row.createCell(2);
                idCardCell.setCellValue(employee.getIdCard());
                //违规项
                Cell alarmType = row.createCell(3);
                alarmType.setCellValue(employee.getEventType() == 15 ? "安全帽监测" : "反光衣监测");
                //违规时间
                Cell alarmTime = row.createCell(4);
                alarmTime.setCellValue(employee.getAlarmTime());

                insertImage(workbook, sheet, employee.getPicUrl(), rowIndex, 5);
                insertImage(workbook, sheet, employee.getPic(), rowIndex, 6);
                rowIndex++;
            }


            // Merge cells by DeptName
            mergeCellsByDeptName(sheet);


            // Write the Excel file
            try (FileOutputStream fileOut = new FileOutputStream("C:\\Users\\aoc\\Desktop\\output.xlsx")) {
                workbook.write(fileOut);
            }

            System.out.println("Excel file created successfully.");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 合并单元格
     *
     * @param sheet
     */
    private static void mergeCellsByDeptName(Sheet sheet) {
        String currentDeptName = "";
        int startRow = 1;
        int startCol = 0;
        int lastRowNum = sheet.getLastRowNum();

        for (Row row : sheet) {
            Cell deptNameCell = row.getCell(0);
            String deptName = deptNameCell.getStringCellValue();

            if (!deptName.equals(currentDeptName)) {
                if (!currentDeptName.isEmpty() && row.getRowNum() - startRow >= 2) {
                    sheet.addMergedRegion(new CellRangeAddress(startRow, row.getRowNum() - 1, startCol, startCol));
                }
                currentDeptName = deptName;
                startRow = row.getRowNum();
            }
        }

        // Check if there are at least two rows in the last merged region
        if (lastRowNum - startRow >= 1) {
            sheet.addMergedRegion(new CellRangeAddress(startRow, lastRowNum, startCol, startCol));
        }
    }

    /**
     * 设置表头
     *
     * @param headerRow
     * @param headers
     */
    private static void setHeaders(Row headerRow, String[] headers) {
        CellStyle headerStyle = headerRow.getSheet().getWorkbook().createCellStyle();
        Font font = headerRow.getSheet().getWorkbook().createFont();
        font.setBold(true);
        headerStyle.setFont(font);

        for (int i = 0; i < headers.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headers[i]);
            cell.setCellStyle(headerStyle);
        }
    }

    /**
     * 插入图片
     *
     * @param workbook
     * @param sheet
     * @param imageUrl
     * @param rowIndex
     * @param colIndex
     */
    private static void insertImage(Workbook workbook, Sheet sheet, String imageUrl, int rowIndex, int colIndex) {
        try {
            CreationHelper helper = workbook.getCreationHelper();
            Drawing<?> drawing = sheet.createDrawingPatriarch();
            ClientAnchor anchor = helper.createClientAnchor();
            anchor.setCol1(colIndex);
            anchor.setRow1(rowIndex);
            anchor.setCol2(colIndex + 1);
            anchor.setRow2(rowIndex + 1);

            // 设置图片大小
            anchor.setAnchorType(ClientAnchor.AnchorType.DONT_MOVE_AND_RESIZE);
            anchor.setAnchorType(ClientAnchor.AnchorType.MOVE_AND_RESIZE);
            anchor.setDx1(0);
            anchor.setDy1(0);
            anchor.setDx2(1000);
            anchor.setDy2(1000);

            URL url = new URL(imageUrl);
            BufferedImage image = ImageIO.read(url);
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            ImageIO.write(image, "jpg", byteArrayOutputStream);
            int pictureIdx = workbook.addPicture(byteArrayOutputStream.toByteArray(), Workbook.PICTURE_TYPE_JPEG);
            byteArrayOutputStream.close();


            drawing.createPicture(anchor, pictureIdx);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    static class Employee {
        private String deptName;
        private String name;
        private String picUrl;

        private String pic;
        private String idCard;
        private String alarmTime;
        private int eventType;

        public Employee(String deptName, String name, String picUrl, String pic, String idCard, String alarmTime, int eventType) {
            this.deptName = deptName;
            this.name = name;
            this.picUrl = picUrl;
            this.pic = pic;
            this.idCard = idCard;
            this.alarmTime = alarmTime;
            this.eventType = eventType;
        }

        public String getDeptName() {
            return deptName;
        }

        public String getName() {
            return name;
        }

        public String getPicUrl() {
            return picUrl;
        }

        public String getPic() {
            return pic;
        }

        public String getIdCard() {
            return idCard;
        }

        public String getAlarmTime() {
            return alarmTime;
        }

        public int getEventType() {
            return eventType;
        }
    }
}

都看到这里了麻烦各位大哥关注一下个人微信公众号,有问题私信我!
在这里插入图片描述

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值