一般Web项目中的需求是先上传文件,再对文件解析将数据取出,文件上传参见我的另一篇博客ajaxFileUpload+struts2文件上传,这里我们只说说Excel文件的解析。
首先,第一步需要导入jar包
xls和csv需要的jar包:poi-3.7.jar
xlsx需要的jar包:poi-ooxml-3.7.jar,poi-ooxml-schemas-3.7.jar,xmlbeans-3.0.0.jar
第二步读取文件,顺序Workbook->Sheet->行->列
public static void main(String[] args) throws IOException {
File excel = new File("D:\\test.csv");
String[] split = excel.getName().split("\\."); //.是特殊字符,需要转义!
Workbook wb;
//根据文件后缀(xls/xlsx)进行判断
if ( "xls".equals(split[1]) || "csv".equals(split[1])){
FileInputStream fiStream = new FileInputStream(excel); //文件流对象
wb = new HSSFWorkbook(fiStream);
}else{
wb = new XSSFWorkbook(new FileInputStream(excel));
}
//开始解析
Sheet sheet = wb.getSheetAt(0); //读取sheet 0
int firstRowIndex = sheet.getFirstRowNum()+1; //第一行是列名,所以不读
int lastRowIndex = sheet.getLastRowNum();
for(int rIndex = firstRowIndex; rIndex <= lastRowIndex; rIndex++) { //遍历行
Row row = sheet.getRow(rIndex);
if (row != null) {
int firstCellIndex = row.getFirstCellNum();
int lastCellIndex = row.getLastCellNum();
for (int cIndex = firstCellIndex; cIndex < lastCellIndex; cIndex++) { //遍历列
Cell cell = row.getCell(cIndex);
if (cell != null) {
System.out.print(cell.toString() + " ");
}
}
System.out.println("");
}
}
}
简单明了的结束……
另外推荐大家在找jar包的时候用maven的仓库,比自己到官网找快多了,不熟悉maven的小伙伴可以尝试先从仓库找jar包开始用起来。