POI处理Excel,获取特定单元格后,为其右侧相邻单元格赋值(Excel签署)
程序员文章站
2024-03-20 23:01:58
...
刚刚接触POI,想要处理Excel的签署,网上百度了好多资料都没有直接相关的例子。
自己根据收集的资料完成了需求,记录一下。
1.开发环境
开发工具:MyEclipse 10;
jar包:POI-3.7等;
2.需求描述
通过POI处理多Sheet页的Excel,每个Excel都有一行作为签署行,每行都有单元格内容为:编制,校对,审核,批准的单元格,但是单元格位置不固定,坐标随机。
需要获取到内容为“编制,校对,审核,批准”的单元格,并在其右侧相邻的单元格进行签署(写入对应的签署人姓名);
3.代码实现
package com.ck.excel;
//引入必要的jar包
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class SignatureExcel {
/**
* @param args
*/
public static String fileString = "test.xlsx";
@SuppressWarnings("rawtypes")
public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub
try {
FileInputStream fs = new FileInputStream(new File(fileString));
FileOutputStream fStream = new FileOutputStream(new File("test1.xlsx"));
XSSFWorkbook wb = new XSSFWorkbook(fs);
//first sheet's index is 0;
XSSFSheet sheet;
XSSFRow row;
XSSFCell cell;
for (Iterator witerator = wb.iterator(); witerator.hasNext();) {
sheet = (XSSFSheet) witerator.next();
for (Iterator rIterator = sheet.rowIterator();rIterator.hasNext();) {
row = (XSSFRow) rIterator.next();
for (Iterator cIterator = row.iterator(); cIterator
.hasNext();) {
cell = (XSSFCell) cIterator.next();
if (!getCellValue(cell).equalsIgnoreCase("") && getCellValue(cell)!=null) {
if(getCellValue(cell).equalsIgnoreCase("编制")){
XSSFCell tCell = row.createCell(cell.getColumnIndex()+1);
tCell.setCellValue("111");
}else if (getCellValue(cell).equalsIgnoreCase("校对")) {
XSSFCell tCell = row.createCell(cell.getColumnIndex()+1);
tCell.setCellValue("222");
}else if (getCellValue(cell).equalsIgnoreCase("审核")) {
XSSFCell tCell = row.createCell(cell.getColumnIndex()+1);
tCell.setCellValue("333");
}else if (getCellValue(cell).equalsIgnoreCase("批准")) {
XSSFCell tCell = row.createCell(cell.getColumnIndex()+1);
tCell.setCellValue("444");
}
}
}
}
}
wb.write(fStream);
fs.close();
fStream.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// 获取单元格的值
public static String getCellValue(XSSFCell cell) {
String value = "";
int cellType = 0;
if (cell != null) {
cellType = cell.getCellType();
//System.out.println("XSSFCell.CELL_TYPE_STRING:"+ XSSFCell.CELL_TYPE_STRING+";cellType:"+cellType);
if (cellType == XSSFCell.CELL_TYPE_STRING) {
//System.out.println("IN EXCEL!!!");
value = cell.getStringCellValue();
}
}
return value;
}
}