我在不同的工作表中有来自同一个Excel的两个表。在表1中:有两列,如“实际值”和“保存值”两列的单元格值如下所示实际值:row(0)2005.99,row(1)6774.00 ...保存的值:row( 0)ClaimsTotal,row(1)ClaimsAServiceTotal
在表2中:有一个名为“Calculations”的列名称“Value1”“Value2”“Value3”Calculations列的单元格值如下所示Calculations:row(0)ClaimsTotal + ClaimsAServiceTotal = ClaimsGrandTotal ..... .etc
我已经编写了excel读写的代码,下面是参考的方法
ExcelReader excelutil = new ExcelReader("Guardian Role");
Object[] savedValue = excelutil.readExcelByColName("Saved Value");
Object[] actualValue = excelutil.readExcelByColName("Actual Value");
ExcelReader readCaliTable = new ExcelReader("Data Verification");
Object[] caliculation = readCaliTable.readExcelByColName("Calculations");
我的要求是:首先我需要拆分表2计算列单元格值,并且需要保留两个不同的字符串,如value [0] = ClaimsTotal和value 1 = ClaimsAServiceTotal。基于这个单元格字符串,我想在表1中保存值列,如果它存在,那么表1实际值列中的对应值需要得到并进行计算Ex:
ClaimsTotal = 2005.99 (I need to print this in table 2 value 1)
ClaimsAServiceTotal= 6774.00 (I need to print this in table 2 value 2)
(2005.99+6774.00)= total (I need to print this in table 2 value 3) like wise in some rows there will be +,=
public ExcelReader(String sheetname, String sheetname1) throws IOException {
super();
this.filename = configProps.getProperty("testData");;
this.sheetname = sheetname;
this.sheetname1 = sheetname1;
this.excelFile = new FileInputStream(new File(this.filename));
this.workbook = new XSSFWorkbook(this.excelFile);
this.sheet = workbook.getSheet(this.sheetname);
this.sheet1 = workbook.getSheet(this.sheetname1);
}
public void verifyData(String colName) throws FileNotFoundException {
Object[] calc = this.readExcelByColName(colName);
for (int i = 0; i < calc.length; i++) {
String string = (String) calc[i];
string = string.replaceAll("\\s", "");
String[] parts = string.split("(\\+)|(\\=)");
int j = 1;
for (String s : parts) {
int[] index1 = findIndex(this.sheet1, s);
int[] index2 = findIndex(this.sheet, string);
this.sheet.getRow(index2[0]).getCell((index2[1] + j))
.setCellValue(this.sheet1.getRow(index1[0]).getCell(index1[1] - 1).getStringCellValue());
j++;
}
}
this.outFile = new FileOutputStream(new File(this.filename));
}
private int[] findIndex(Sheet sheet, String cellContent) {
for (Row row : sheet) {
for (Cell cell : row) {
if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
if (cell.getStringCellValue().replaceAll("\\s", "").equals(cellContent)) {
int[] index = { row.getRowNum(), cell.getColumnIndex() };
return index;
}
}
}
}
return null;
}
主要方法@ Test
ExcelReader excelUtil2 = new ExcelReader("Verify Data","Guardian Angel Hospice");
excelUtil2.verifyData("Calculations");
Object[] data2 = excelUtil2.readExcelByColName("Value1");
for (int i = 0; i < data2.length; i++) {
System.out.println(data2[i]);
}
excelUtil2.saveAndCloseExcel();
PFA Excel