Java读写Excel的包是Apache POI(项目地址:http://poi.apache.org/),因此需要先获取POI的jar包,本实验使用的是POI 3.9稳定版。
Apache POI 代码例子地址:http://poi.apache.org/spreadsheet/quick-guide.html
本例子可以读取Microsoft Office Excel 2003/2007/2010,具体代码及注释如下:
读取“.xls”格式使用 import org.apache.poi.hssf.usermodel.*;包的内容,例如:HSSFWorkbook
读取“.xlsx”格式使用 import org.apache.poi.xssf.usermodel.*; 包的内容,例如:XSSFWorkbook
读取两种格式使用 import org.apache.poi.ss.usermodel.* 包的内容,例如:Workbook
引入包如下:
- import org.apache.poi.ss.usermodel.Cell;
- import org.apache.poi.ss.usermodel.Row;
- import org.apache.poi.ss.usermodel.Sheet;
- import org.apache.poi.ss.usermodel.Workbook;
- import org.apache.poi.ss.usermodel.WorkbookFactory;
- import org.apache.poi.ss.usermodel.DateUtil;
-
-
-
- public String readExcel()
- {
- SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
- try {
-
- File excelFile = new File("/home/zht/test.xls");
- FileInputStream is = new FileInputStream(excelFile);
- Workbook workbook = WorkbookFactory.create(is);
- int sheetCount = workbook.getNumberOfSheets();
-
- for (int s = 0; s < sheetCount; s++) {
- Sheet sheet = workbook.getSheetAt(s);
- int rowCount = sheet.getPhysicalNumberOfRows();
-
- for (int r = 0; r < rowCount; r++) {
- Row row = sheet.getRow(r);
- int cellCount = row.getPhysicalNumberOfCells();
-
- for (int c = 0; c < cellCount; c++) {
- Cell cell = row.getCell(c);
- int cellType = cell.getCellType();
- String cellValue = null;
- switch(cellType) {
- case Cell.CELL_TYPE_STRING:
- cellValue = cell.getStringCellValue();
- break;
- case Cell.CELL_TYPE_NUMERIC:
- if(DateUtil.isCellDateFormatted(cell)) {
- cellValue = fmt.format(cell.getDateCellValue());
- }
- else {
- cellValue = String.valueOf(cell.getNumericCellValue());
- }
- break;
- case Cell.CELL_TYPE_BOOLEAN:
- cellValue = String.valueOf(cell.getBooleanCellValue());
- break;
- case Cell.CELL_TYPE_BLANK:
- cellValue = cell.getStringCellValue();
- break;
- case Cell.CELL_TYPE_ERROR:
- cellValue = "错误";
- break;
- case Cell.CELL_TYPE_FORMULA:
- cellValue = "错误";
- break;
- default:
- cellValue = "错误";
- }
- System.out.print(cellValue + " ");
- }
- System.out.println();
- }
- }
-
- }
- catch (Exception e) {
- e.printStackTrace();
- }
-
- return Action.SUCCESS;
- }