我有一个看起来像这样的 Excel 电子表格:
+-----------------+--------+----------------------+
| Title | Value | Average Price List |
+-----------------+--------+----------------------+
| | | |
| Item 1 | 10 | 9.99 |
| Item 2 | 20 | 9.99 |
| Item 3 | 30 | 8.99 |
| Total Royalty A | | |
| | | |
+-----------------+--------+----------------------+
| Item 1 | 10 | 9.90 |
| Item 2 | 20 | 5.69 |
| Item 3 | 30 | 9.99 |
| Total Royalty B | | |
| | | |
+-----------------+--------+----------------------+
我想获得平均列的总值。但是,我需要使用“总版税A”和“总版税B”将总数分开;这意味着最终结果应该是这样的:
Total Royalty A = 10.99
Total Royalty B = 11.88
我使用了一个 HashMap,其中键是“总版税 A”和“总版税 B”。我的 if 语句中的代码出现问题:
if(totalCell.getCellType() == Cell.CELL_TYPE_STRING)
我认为问题是标题下有一个空/空白单元格。我尝试使用不同的技术来跳过空单元格,但问题仍然发生在该线上。如果有人能给我关于如何解决这个问题的任何建议,我将不胜感激。
这是应该处理上述操作的方法:
public HashMap monthlyAverageUnitsTotal (HSSFSheet sheet, int colAvgNum, int colTitle )
{
HashMap hm = new HashMap();
double sum = 0.0;
String key = null;
for(Row row : sheet)
{
Cell saleAverageCell = row.getCell(colAvgNum);
Cell totalCell = row.getCell(colTitle);
if(totalCell.getCellType() == Cell.CELL_TYPE_STRING)
{
String totalCellValue = totalCell.getStringCellValue().toString().trim();
if(totalCellValue.startsWith("Total Royalty"))
{
key = totalCell.getStringCellValue().toString().trim();
}
}
if(saleAverageCell.getCellType() == Cell.CELL_TYPE_NUMERIC)
{
double saleAverageCellValue = saleAverageCell.getNumericCellValue();
sum += saleAverageCellValue;
// put the element in the map
hm.put(key, sum);
// return the value of sum to 0
sum = 0.0;
}
}
return hm;
}
最佳答案
我有一个功能要求,涉及解析包含大量数据的 Excel 电子表格。为了利用单元格值问题,我创建了一个以字符串格式返回单元格值的函数,因此我不会遇到字符串、数字、日期、 boolean 值或空白单元格的问题(它不处理公式值):
//Cell celdaActual is the actual cell in a row in a sheet in the book, the class
//has Spanish names and comments and is big for a post, so I'm just posting
//this function
public String getCellValue() {
String strValor = "";
int intValor;
double dblValor;
SimpleDateFormat objSimpleDateFormat;
if (celdaActual != null) {
strValor = celdaActual.toString();
switch (celdaActual.getCellType()) {
case Cell.CELL_TYPE_STRING:
strValor = strValor.trim();
break;
case Cell.CELL_TYPE_NUMERIC:
if (DateUtil.isCellDateFormatted(celdaActual)) {
objSimpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");
strValor = objSimpleDateFormat
.format(celdaActual.getDateCellValue());
} else {
dblValor = celdaActual.getNumericCellValue();
if (Math.floor(dblValor) == dblValor) {
intValor = (int)dblValor;
strValor = String.valueOf(intValor);
} else {
strValor = String.valueOf(dblValor);
}
}
break;
case Cell.CELL_TYPE_BLANK:
strValor = "";
break;
case Cell.CELL_TYPE_ERROR:
strValor = "";
break;
case Cell.CELL_TYPE_BOOLEAN:
strValor = String.valueOf(celdaActual.getBooleanCellValue());
break;
}
}
return strValor;
}
希望它对您有用。
关于java - Apache POI : Storing key and sum in a Map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10824312/