本文概览:介绍了java通过poi解析excel。
1、引入maven
1 2 3 4 5 |
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.16</version> </dependency> |
2、代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
public class ExportBlackCodeFee { public void readExcel(String path) throws IOException { // 获取文件流 InputStream is = new FileInputStream(path); HSSFWorkbook hssfWorkbook = new HSSFWorkbook(is); // 获取所有sheet for (int numSheet = 0; numSheet < hssfWorkbook.getNumberOfSheets(); numSheet++) { HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(numSheet); if (hssfSheet == null) { continue; } // 处理一个sheet。第一行是字段名称,直接跳过,所以rowNum从1开始 for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) { HSSFRow hssfRow = hssfSheet.getRow(rowNum); if (hssfRow != null) { // 1.number类型都是double类型,如果需要int,则需要转一下 HSSFCell blackCodeCell = hssfRow.getCell(1); int blackCode = (int) blackCodeCell.getNumericCellValue(); System.out.println(blackCode); // 2.通道name.String类型 HSSFCell blackCodeNameCell = hssfRow.getCell(2); String blackCodeName = blackCodeNameCell.getStringCellValue(); System.out.println(blackCodeName);; // 3.日期类型 HSSFCell validDateCell = hssfRow.getCell(4); String validDate = DateUtils.format(endValidDateCell.getDateCellValue(), DateUtils.DATE_FORMAT); System.out.println(validDate); // 4.区分string还是string类型 HSSFCell feeInfoCell = hssfRow.getCell(13); String feeInfo; if (feeInfoCell.getCellTypeEnum().equals(CellType.STRING)) { feeInfo = feeInfoCell.getStringCellValue(); } else { feeInfo = feeInfoCell.getNumericCellValue() + ""; } System.out.println(feeInfo); } } } } public static void main(String[] args) throws IOException { ExportBlackCodeFee exportBlackCodeFee = new ExportBlackCodeFee(); exportBlackCodeFee.readExcel("/Users/HeartThindkDo/Desktop/export.xls"); } } |
3、遇到问题
(1)问题描述
java.io.IOException: Invalid header signature; read 0xE4BCB1CABBBDC9B3, expected 0xE11AB1A1E011CFD0 – Your file appears not to be a valid OLE2 document
(2)问题解决
把exel文件另存为如下格式就可以了
(全文完)