java 读取excel文件

POI-Excel写
1、首先可以创建一个普通的maven项目
<!-- 导入poi依赖,对excel 2003的支持依赖(xls) --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>5.0.0</version> </dependency> <!-- poi对于excel 2007的支持依赖(xlsx) --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>5.0.0</version> </dependency>


import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;



import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;



//public class ReadFileExample {
//    public static void main(String[] args) {
//        String fileName = "Forster/example.txt"; // 要读取的文件名
//
//        try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
//            String line;
//
//            while ((line = reader.readLine()) != null) {
//                System.out.println(line); // 输出每行内容
//            }
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }
//}


public class ReadFileExample {
    public static void main(String[] args) {
        String excelFilePath = "Forster/file.xlsx";
        try (FileInputStream inputStream = new FileInputStream(new File(excelFilePath));
             Workbook workbook = new XSSFWorkbook(inputStream)) {

            Sheet sheet = workbook.getSheetAt(0); // 读取第一个工作表
            for (Row row : sheet) { // 迭代每一行
                for (Cell cell : row) { // 迭代每一列
                    // 根据不同数据类型,以字符串形式输出数据

                    switch (cell.getCellType()) {
                        case STRING:
                            System.out.print(cell.getStringCellValue() + "\t");
                            break;
                        case NUMERIC:
                            System.out.print(cell.getNumericCellValue() + "\t");
                            break;
                        case BOOLEAN:
                            System.out.print(cell.getBooleanCellValue() + "\t");
                            break;
                        case FORMULA:
                            System.out.print(cell.getCellFormula() + "\t");
                            break;
                        default: break;
                    }
                }
                System.out.println(); // 换行,表示一行数据结束
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

需要的包

 

 

参考文档 https://zhuanlan.zhihu.com/p/603180908

 
posted @ 2024-04-03 16:14  雪山狼  阅读(24)  评论(0编辑  收藏  举报