功能描述:
在已有的excel中末行位置追加审批链岗位及对应审批人的签名
功能实现:
package org.example;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xssf.usermodel.*;
import java.io.*;
public class excelImageTest {
public static void main(String[] args) throws IOException {
// 打开文件流
FileInputStream fileInputStream = new FileInputStream("C:/Users/A.xlsx");
// 创建工作簿对象
Workbook workbook = new XSSFWorkbook(fileInputStream);
// 创建工作表
Sheet sheet = workbook.getSheetAt(0);
// 读取最后一行的行号,以获取空行数
int emptyRowCount = 0;
for (int i = 0; i >= 0; i++) { // 从最后一行开始向前遍历所有行
Row row = sheet.getRow(i); // 获取第i行对象
if (row == null || row.getPhysicalNumberOfCells() == 0) { // 如果该行是空行或没有单元格,则增加空行计数器
emptyRowCount = i;
break;
}
}
int physicalNumberOfCells = sheet.getRow(0).getPhysicalNumberOfCells();
System.out.println(physicalNumberOfCells);
for (int i = physicalNumberOfCells ; i < 5*2; i++) {
sheet.setColumnWidth(i,sheet.getColumnWidth(0));
}
// 创建行
Row row = sheet.createRow(emptyRowCount + 1);
for (int i = 0; i < 5; i++) {
// 创建单元格并设置值
Cell cell1 = row.createCell(i*2);
cell1.setCellValue("部门主要负责人");
// 创建单元格并设置值
Cell cell = row.createCell(i*2+1);
// 读取图片文件并获取输入流
InputStream inputStream = new FileInputStream("C:/Users/chens/Pictures/Saved Pictures/5fce7df964894735be9a0e11ca112068.png");
byte[] bytes = IOUtils.toByteArray(inputStream);
int pictureIdx = workbook.addPicture(bytes, Workbook.PICTURE_TYPE_JPEG);
// 创建图片数据区域
CreationHelper helper = workbook.getCreationHelper();
Drawing drawing = sheet.createDrawingPatriarch();
ClientAnchor anchor = helper.createClientAnchor();
anchor.setCol1(cell.getColumnIndex());
anchor.setRow1(cell.getRowIndex());
Picture pict = drawing.createPicture(anchor, pictureIdx);
// 根据需要调整图片大小
pict.resize(0.8,2.618);
}
// 写入到文件
FileOutputStream fileOut = new FileOutputStream("C:/Users/B.xlsx");
workbook.write(fileOut);
fileOut.close();
fileInputStream.close();
}
}