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 @   雪山狼  阅读(35)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 实操Deepseek接入个人知识库
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· 【.NET】调用本地 Deepseek 模型
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
历史上的今天:
2018-04-03 Jmeter读取文件中的值
点击右上角即可分享
微信分享提示