利用apache.poi 在Excel中插入图片、自适应宽高

文章目录

目录

文章目录

前言

一、使用步骤

1、引入poi相关jar包

2、相关代码示例

3、效果展示 

总结


前言

Apache POI是一个开源的Java库,用于读取和写入Microsoft Office格式(例如Word,Excel和PowerPoint)的文件。它提供了一组API,使开发人员可以与这些文件进行交互,包括创建新文件、读取和修改现有文件以及将文件导出为其他格式(如PDF)。Apache POI支持各种Office文件格式,包括.doc,.docx,.xls,.xlsx和.ppt。它是一个非常强大和灵活的库,被广泛用于Java应用程序中处理Office文件。


一、使用步骤

1、引入poi相关jar包

<dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.17</version>
</dependency>

2、相关代码示例

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.ClientAnchor;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.Drawing;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Picture;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.util.IOUtils;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author: youchao
 * @description:
 * @data: 2024/1/31 15:24
 **/
public class AddPicToExcel {
    //Excel所在位置
    private static final String EXCEL_PATH = "";

    //Excel下载位置
    private static final String DOWNLOADFILE_PATH = "";

    //图片所在位置
    private static final String PIC_PATH = "";

    public static void main(String[] args) throws Exception {
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            fileInputStream = new FileInputStream(EXCEL_PATH);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        //读取Excel
        HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream);
        HSSFSheet sheetAt = workbook.getSheetAt(0);
        HSSFRow row = sheetAt.getRow(sheetAt.getLastRowNum());
        //设置单元格样式
        HSSFCellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setAlignment(HorizontalAlignment.RIGHT);
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        setBorder(cellStyle, BorderStyle.THIN, IndexedColors.BLACK);

        //写入数据并插入图片
        HSSFCell preparationCell = row.getCell(1);
        preparationCell.setCellValue("2024-01-31");
        preparationCell.setCellStyle(cellStyle);
        picture2(workbook, sheetAt, PIC_PATH, sheetAt.getLastRowNum(), 1, 0.6, 1);

        //自定义宽高
        for (int i = 0; i < 9; i++) {
            sheetAt.autoSizeColumn(i);
            sheetAt.setColumnWidth(i, sheetAt.getColumnWidth(i) * 17 / 10);
        }

        //输出excel
        fileOutputStream = new FileOutputStream(DOWNLOADFILE_PATH);
        try {
            workbook.write(fileOutputStream);
            fileOutputStream.close();
            fileInputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * @param cellStyle  单元格样式对象
     * @param borderSize
     * @param colorIndex
     * @Title: setBorder
     * @Description: 设置单元格边框
     * @author: youchao
     * @date 2024年1月31日
     * @version
     */

    public static CellStyle setBorder(CellStyle cellStyle, BorderStyle borderSize, IndexedColors colorIndex) {
        cellStyle.setBorderBottom(borderSize);
        cellStyle.setBottomBorderColor(colorIndex.index);
        cellStyle.setBorderLeft(borderSize);
        cellStyle.setLeftBorderColor(colorIndex.index);
        cellStyle.setBorderRight(borderSize);
        cellStyle.setRightBorderColor(colorIndex.index);
        cellStyle.setBorderTop(borderSize);
        cellStyle.setTopBorderColor(colorIndex.index);
        return cellStyle;
    }


    /**
     * @param workbook workbook对象
     * @param sheet    工作簿对象
     * @param fileUrl  URL
     * @param row      第多少行
     * @param col      第多少列
     * @param scaleX   X轴
     * @param scaleY   Y轴
     * @Title: picture2
     * @Description: 图片插入至单元格
     * @author: youchao
     * @date 2024年1月31日
     * @version
     */
    public static void picture2(org.apache.poi.ss.usermodel.Workbook workbook, Sheet sheet, String fileUrl, int row, int col, double scaleX, double scaleY) {
        try {
            // 输入流
            InputStream is = null;
            try {
                is = new FileInputStream(fileUrl);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            byte[] bytes = IOUtils.toByteArray(is);
            @SuppressWarnings("static-access")
            int pictureIdx = workbook.addPicture(bytes, workbook.PICTURE_TYPE_PNG);
            CreationHelper helper = workbook.getCreationHelper();
            Drawing drawing = sheet.createDrawingPatriarch();
            ClientAnchor anchor = helper.createClientAnchor();
            // 图片插入坐标
            anchor.setCol1(col);
            anchor.setRow1(row);
            // 插入图片
            Picture pict = drawing.createPicture(anchor, pictureIdx);
            pict.resize(scaleX, scaleY);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

3、效果展示 

  效果图讲解:

  1. 模板为自定义模板 根据业务需求 利用POI生成模板 。
  2. 1、2行为图片,方法同上示例代码。
  3. 17行第二列为示例代码效果,签名为图片,日期为文本,插入至同一个单元格中。

总结

        以上就是今天要讲解的内容,本文仅仅简单介绍了poi插入图片的使用,而Apache POI支持各种Office文件格式。它提供了一组API,使开发人员可以与这些文件进行交互,包括创建新文件、读取和修改现有文件以及将文件导出为其他格式(如PDF)。欢迎各位小伙伴来交流讨论,一起努力一起进步。下期见,一个热爱搬砖的互联网民工!!!

  • 25
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
以下是使用Apache POI复制Excel sheet并保留格式的代码示例: ```java import java.io.FileOutputStream; import java.io.IOException; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class CopyExcelSheet { public static void main(String[] args) { try (Workbook workbook = new XSSFWorkbook("original.xlsx"); FileOutputStream fileOut = new FileOutputStream("copy.xlsx")) { // 获取要复制的sheet Sheet originalSheet = workbook.getSheet("Sheet1"); // 创建新的sheet并设置sheet名称 Sheet copiedSheet = workbook.createSheet("Copy of Sheet1"); // 复制行和列 for (int rowIndex = 0; rowIndex < originalSheet.getLastRowNum(); rowIndex++) { Row originalRow = originalSheet.getRow(rowIndex); Row copiedRow = copiedSheet.createRow(rowIndex); if (originalRow != null) { for (int colIndex = 0; colIndex < originalRow.getLastCellNum(); colIndex++) { Cell originalCell = originalRow.getCell(colIndex); Cell copiedCell = copiedRow.createCell(colIndex); if (originalCell != null) { // 复制单元格值 copiedCell.setCellValue(originalCell.getStringCellValue()); // 复制单元格样式 CellStyle originalCellStyle = originalCell.getCellStyle(); CellStyle copiedCellStyle = workbook.createCellStyle(); copiedCellStyle.cloneStyleFrom(originalCellStyle); copiedCell.setCellStyle(copiedCellStyle); } } } } // 保存工作簿 workbook.write(fileOut); } catch (IOException e) { e.printStackTrace(); } } } ``` 在此示例,我们首先打开原始Excel文件并获取要复制的sheet。然后,我们创建一个新的sheet并将其命名为“Copy of Sheet1”。接下来,我们循环遍历原始sheet的所有行和列,并将它们复制到新的sheet。对于每个单元格,我们复制单元格值并复制单元格样式。最后,我们将工作簿写入新的Excel文件。 请注意,这只是一个基本示例,您可能需要根据自己的需求进行修改和优化。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AKYChao

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值