样例程序如下所示,其中:
- parseXls()函数依赖于jxl,只能读取xls格式文件;
- parseExcel()函数依赖于apache poi,能够读取xls和xlsx两种格式的文件。
jxl的依赖:
<!-- https://mvnrepository.com/artifact/net.sourceforge.jexcelapi/jxl -->
<dependency>
<groupId>net.sourceforge.jexcelapi</groupId>
<artifactId>jxl</artifactId>
<version>2.6.12</version>
</dependency>
apache poi的依赖:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.10-FINAL</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.10-FINAL</version>
</dependency>
示例代码:
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import jxl.Sheet;
import jxl.Workbook;
public class ExcelParser {
public List<List<String>> parseXls(File file) {
try {
Workbook workbook = Workbook.getWorkbook(file);
Sheet sheet = workbook.getSheet(0);
List<List<String>> list = new ArrayList<List<String>>();
for (int i = 0; i < sheet.getRows(); i++) {
List<String> rowList = new ArrayList<String>();
for (int j = 0; j < sheet.getColumns(); j++) {
rowList.add(sheet.getCell(j, i).getContents());
}
list.add(rowList);
}
// test
for (List<String> rowList : list) {
for (String s : rowList)
System.out.print(s + ",");
System.out.println();
}
return list;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public List<List<String>> parseExcel(File file) {
try {
InputStream fis = new FileInputStream(file);
String fileName = file.getName();
org.apache.poi.ss.usermodel.Workbook workbook = null;
if (fileName.toLowerCase().endsWith("xlsx")) {
workbook = new XSSFWorkbook(fis);
} else if (fileName.toLowerCase().endsWith("xls")) {
workbook = new HSSFWorkbook(fis);
}
org.apache.poi.ss.usermodel.Sheet sheet = workbook.getSheetAt(0);
List<List<String>> list = new ArrayList<List<String>>();
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
List<String> rowList = new ArrayList<String>();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
switch(cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
rowList.add("" + cell.getNumericCellValue());
break;
case Cell.CELL_TYPE_STRING:
default:
rowList.add(cell.getStringCellValue());
break;
}
}
list.add(rowList);
}
// test
for (List<String> rowList : list) {
for (String s : rowList)
System.out.print(s + ",");
System.out.println();
}
return list;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static void main(String[] args) {
new ExcelParser().parseExcel(new File("C:\Users\zifeiy\Documents\zifeiy.xlsx"));
}
}