Java解析Excel文件

1 添加依赖

.xls格式的excel文件需要HSSF支持,需要相应的poi.jar,.xlsx格式的excel文件需要XSSF支持,需要poi-ooxml.jar,

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.17</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.17</version>
        </dependency>
2 解析
/**
     * 根据不同的格式获取不同的对象
     *
     * @param in       输入流
     * @param fileName 文件名
     * @return Excel的对象
     * @throws Exception
     */
    public Workbook getWorkbook(InputStream in, String fileName) throws Exception {
        Workbook workbook = null;
        String fileType = fileName.substring(fileName.lastIndexOf("."));//获得后缀
        if (".xls".equals(fileType)) {
            workbook = new HSSFWorkbook(in);
        } else if (".xlsx".equals(fileType)) {
            workbook = new XSSFWorkbook(in);
        } else {
            throw new Exception("请上传excel文件!");
        }
        return workbook;
    }
    
	public void readExcel(InputStream in, String fileName){
		 try {
	            Workbook wb = getWorkbook(in, fileName);//获得正确的流
	            //获取第一个sheet页
                Sheet sheet=  wb.getSheetAt(0);
	            int firstRowIndex = sheet.getFirstRowNum()+1;   //第一行是列名,所以不读
	                int lastRowIndex = sheet.getLastRowNum();
	                System.out.println("firstRowIndex: "+firstRowIndex);
	                System.out.println("lastRowIndex: "+lastRowIndex);
	
	                for(int rIndex = firstRowIndex; rIndex <= lastRowIndex; rIndex++) {   //遍历行
	                    System.out.println("rIndex: " + rIndex);
	                    Row row = sheet.getRow(rIndex);
	                    if (row != null) {
	                        int firstCellIndex = row.getFirstCellNum();
		                    int lastCellIndex = row.getLastCellNum();
		                    System.out.println("firstCellIndex = " + firstCellIndex + ".lastCellIndex = " + lastCellIndex);
		                    for (int cIndex = firstCellIndex; cIndex < lastCellIndex; cIndex++) {   //遍历列
		                        Cell cell = row.getCell(cIndex);
		                        if (cell != null) {
		                            System.out.print(getCellFormatValue(cell) + " ");
		                        }
		                    }
		                }
		                System.out.println();
	                }
	 	} catch (Exception e) {
	          e.printStackTrace();
	    }
 }
 
 public Object getCellFormatValue(Cell cell) {
        Object cellValue = null;
        if (cell == null) {
            return "";
        }

        //cell 类型
        CellType cellType = cell.getCellTypeEnum();

        // 判断cell类型
        switch (cellType) {
            //数字类型
            case NUMERIC: {
                cellValue = NumberToTextConverter.toText(cell.getNumericCellValue());
                break;
            }
            //字符串类型
            case STRING: {
                cellValue = cell.getRichStringCellValue().getString();
                break;
            }
            //空
            case BLANK: {
                cellValue = "";
                break;
            }
            default:
                System.out.println("无法解析的类型");
                cellValue = "";
        }
        return cellValue;
    }
3 Controller调用
@PostMapping("/uploadExcel")
    public void uploadExcel(@RequestBody MultipartFile file)  {
        try {
            InputStream inputStream = file.getInputStream();
            excelImportService.readExcel(inputStream, file.getOriginalFilename());
            inputStream.close();
        } catch (Exception ex) {
        }
    }

参考博客:https://blog.csdn.net/gxx_csdn/article/details/79085713

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Java中,可以使用Apache POI库来解析Excel文件。Apache POI是一个开源的Java库,提供了读取、写入和操作Microsoft Office格式文件(如Excel、Word和PowerPoint)的功能。 要解析Excel文件,首先需要导入Apache POI库的相关依赖。可以在项目的pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.1.2</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.1.2</version> </dependency> ``` 接下来,可以使用以下代码示例来解析Excel文件: ```java import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.FileInputStream; import java.io.IOException; public class ExcelParser { public static void main(String[] args) { try { FileInputStream file = new FileInputStream("path/to/excel/file.xlsx"); Workbook workbook = new XSSFWorkbook(file); Sheet sheet = workbook.getSheetAt(0); for (Row row : sheet) { for (Cell cell : row) { CellType cellType = cell.getCellType(); if (cellType == CellType.STRING) { System.out.print(cell.getStringCellValue() + "\t"); } else if (cellType == CellType.NUMERIC) { System.out.print(cell.getNumericCellValue() + "\t"); } else if (cellType == CellType.BOOLEAN) { System.out.print(cell.getBooleanCellValue() + "\t"); } } System.out.println(); } workbook.close(); file.close(); } catch (IOException e) { e.printStackTrace(); } } } ``` 上述代码使用FileInputStream来读取Excel文件,然后创建XSSFWorkbook对象表示整个Excel文件。通过getSheetAt方法获取第一个Sheet,然后使用两个嵌套的循环遍历每一行和每一个单元格。根据单元格的类型,可以使用getCellType方法获取单元格的值。 请注意,上述代码示例假设Excel文件的第一个Sheet是要解析的目标。如果需要解析其他Sheet,可以使用getSheet方法指定Sheet的名称或索引。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值