POI - the Java API for Microsoft Documents
1.在Apache官网下载Apache最新poi版本:poi-bin-3.11-20141221.zip,解压;
这里要注意是在binary distribution 下载,binary distribution是jar包,source distribution是包含源文件的,可以打开java代码
2.在Eclipse中引入jar包:project—properties—Libraries—Add External JARs
Apache官网提供了一些例子:http://poi.apache.org/spreadsheet/quick-guide.html
注意:使用POI扩展包的时候出现“POI java.lang.NoClassDefFoundError: org/apache/xmlbeans/XmlException”异常,一般是由于POI的其中一个名为“xmlbeans-2.3.0.jar”(或其他版本)的扩展包没有添加到项目的Library里面。在poi-3.11中是在ooxml-lib
Example Code:(以读取桌面excel交易表为例,路径由dataPath传入)
public static Map<String, ArrayList<String>> readExcelData(String dataPath) throws IOException {
InputStream is = new FileInputStream(dataPath);
@SuppressWarnings("resource")
XSSFWorkbook wb = new XSSFWorkbook(is);
XSSFSheet sheet = wb.getSheetAt(0); // 获取第一个sheet表
XSSFRow rowData;
Map<String, ArrayList<String>> resultData = new HashMap<String, ArrayList<String>>();
String trans_key = null;
String item;
for (int i = sheet.getTopRow(); i < sheet.getLastRowNum() + 1; i++) {
rowData = sheet.getRow(i);
if (i == sheet.getTopRow()) {
continue; //标题不读入
}
ArrayList<String> trans_item = new ArrayList<String>();
for (int j = rowData.getFirstCellNum(); j < rowData.getLastCellNum(); j++) {
if (j == rowData.getFirstCellNum()) {
trans_key = rowData.getCell(j).toString();
} else {
item = rowData.getCell(j).toString();
trans_item.add(item);
}
}
resultData.put(trans_key, trans_item);
}
is.close();
return resultData;
}
TODO:有个小问题,
rowData.getLastCellNum()返回的时列数,比如里面有两列,则返回2;但是sheet.getLastRowNum()却不是行数,而是最后一行的位置,如果要活的确切行数的话,则需要+1;