poi 读写Excel小工具 部分源代码
功能 如果匹配条件相同 则把路径2 的值赋值到路径一
部分源代码
//获取表名
public static String[] getSheetNames(String filePath) {
String[] s = null;
Workbook wb1 = null;
InputStream in = null;
try {
in = new FileInputStream(filePath);
wb1 = WorkbookFactory.create(in);
s = new String[wb1.getNumberOfSheets()];
for (int i = 0; i < wb1.getNumberOfSheets(); i++) {
s[i] = wb1.getSheetName(i);
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "当前excel表不能解析~" + filePath,
"错误", JOptionPane.ERROR_MESSAGE);
} finally {
try {
wb1.close();
in.close();
} catch (Exception e2) {
}
}
return s;
}
public boolean transferSimple(String path1, String path2,
String sheetname1, String sheetname2, List<String> mates,
String[] values, String follow) {
// 记录空行
List<Integer> nullRow = new ArrayList<Integer>();
POIExcelUtil a = new POIExcelUtil(path1.trim());
POIExcelUtil b = new POIExcelUtil(path2.trim());
// 获取表民
Sheet s1 = a.wb.getSheet(sheetname1.trim());
Sheet s2 = b.wb.getSheet(sheetname2.trim());
isSheetNull(s1, s2);
// 匹配条件 mate A:B C:D 匹配赋值必须有: 没有则程序提前结束
if (!mateString(mates, values)) {
return false;
}
// map 存数据 使存入的数据有序
Map<String, LinkedList<String>> map = new LinkedHashMap<String, LinkedList<String>>();
// 左表和元数据进行匹配 相同存入map
for (int i = 0; i <= s1.getLastRowNum(); i++) {
Row row1 = s1.getRow(i);
// 获取 aindex1的系列值 aindex2 aindex3
String cellvalue1 = "";
boolean isNull = false;
// 根据匹配条件去拼接
for (int k = 0; k < mates.size(); k++) {
String p = mates.get(k).split(":")[0];
int index1 = columnNumber(p);
// 出现空指针异常
Cell cell1 = null;
try {
cell1 = row1.getCell(index1);
} catch (NullPointerException e) {
// TODO: handle exception 如果 getCell如果为空行 解决问题
System.out.println("出现空行问题");
isNull = true;
}
// 先设置Cell的类型,然后就可以把纯数字作为String类型读进来了
if (null != cell1) {
setCellType(cell1);
if (null == cell1.getStringCellValue()
|| "".equals(cell1.getStringCellValue())) {
cellvalue1 += " ||";
} else {
cellvalue1 += cell1.getStringCellValue() + "||";
}
} else {
cellvalue1 += " ||";
}
}
// 如果出现空指针异常 也就是空行
if (isNull) {
// 记录空行 循环结束
nullRow.add(i);
continue;
}
// 如果匹配成功 mateId++ 如果一直匹配不到 mateId=0 ->map+
matesALl(mates, values, s2, map, cellvalue1, follow, row1);
// 遍历 row2把 row2这一行存入linkedList H I
}
if (isString(follow)) {
transferPOIwritee(a, sheetname1, map, mates, values, nullRow,
follow);
} else {
transferPOIwritee(a, sheetname1, map, mates, values, nullRow);
}
return true;
}