我正在开发一个将打开excel文件,迭代工作表的行并计算每行数值总计的应用程序。
考虑以下两种情况:
如果第一种情况的输出是:
A -> 15.0 pages.
B -> 15.0 pages.
T -> 15.0 pages.
为什么在第二种情况下的输出是:
Tanmay -> 15.0 pages.
Abhishek -> 15.0 pages.
Bijoy -> 15.0 pages.
不应该如下吗?
Abhishek -> 15.0 pages.
Bijoy -> 15.0 pages.
Tanmay -> 15.0 pages.
package miscellaneous;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* Created by Sandeep on 8/6/15.
*/
public class TestHarness {
@SuppressWarnings({ "unchecked" })
public static void main(String[] args) {
Map<String, Double> stringDoubleMap = new HashMap<String, Double>();
stringDoubleMap = readExcelFile();
for (Map.Entry<String, Double> entry : stringDoubleMap.entrySet()) {
System.out.println(entry.getKey() + " -> " + entry.getValue() + " pages.");
}
}
@SuppressWarnings("rawtypes")
private static Map readExcelFile() {
InputStream fileInputStream = null;
HSSFWorkbook hssfWorkbook = null;
HSSFSheet sheet;
HSSFRow row;
HSSFCell cell;
Iterator rowIterator, cellIterator;
String employeeName=null;
String sheetName=null;
double total=0;
Map<String, Double> empMonthlyProdStat = new HashMap<String, Double>();
try {
fileInputStream = new FileInputStream("D:\\Sandeep\\TestExcelWorkbook.xls");
hssfWorkbook = new HSSFWorkbook(fileInputStream);
sheet = hssfWorkbook.getSheetAt(0);
sheetName = sheet.getSheetName();
rowIterator = sheet.rowIterator();
while (rowIterator.hasNext()) {
row = (HSSFRow) rowIterator.next();
cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
cell = (HSSFCell) cellIterator.next();
if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
employeeName = cell.getStringCellValue();
} else if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
total = total + cell.getNumericCellValue();
} else {// Handle Boolean, Formula, Errors
}
}
empMonthlyProdStat.put(employeeName, total);
total = 0;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
hssfWorkbook.close();
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println(sheetName + "\n" + "------------");
return empMonthlyProdStat;
}
}
由于HashMap不会按其插入顺序返回条目,因此该顺序已关闭。尝试改用LinkedHashMap。
从文档中:
Map接口的哈希表和链表实现,具有可预测的迭代顺序。此实现与HashMap的不同之处在于,它维护一个贯穿其所有条目的双向链接列表。此链表定义了迭代顺序,通常是将键插入映射的顺序(插入顺序)。请注意,如果将密钥重新插入到映射中,则插入顺序不会受到影响。(如果在调用之前m.containsKey(k)将立即返回true的情况下调用了m.put(k,v),则将密钥k重新插入到映射m中。)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句