简体   繁体   English

如何从Java中的src / test / resources中读取Excel文件

[英]How to read a excel file from src/test/resources in Java

I am trying to read an excel file for testing from test/resources, but i keep getting the FileNotFoundException . 我正在尝试从测试/资源中读取一个Excel文件进​​行测试,但是我一直在获取FileNotFoundException I have tried these two approaches, both seem to be giving the same FileNotFoundException . 我尝试了这两种方法,似乎都给出了相同的FileNotFoundException

File decisionConfig=new File("src/test/resources/mapping.xls");
File decisionConfig=new File("classpath:test/resources/mapping.xls");

You can try this: 您可以尝试以下方法:

ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream inputStream = classLoader.getResourceAsStream("test/resources/mapping.xls");

This should get the file based upon the ClassLoader as long as the test directory is in your src folder. 只要test目录位于您的src文件夹中,就应该基于ClassLoader获取文件。 This will get the InputStream for the file. 这将获取文件的InputStream

*********************************UPDATE************************************ For File object: ********************************* UPDATE **************** ********************对于File对象:

ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
File file = new File(classLoader.getResource("test/resources/mapping.xls").toString());

I'm not sure what exactly you want do with this file but for Microsoft Office files I like to use Apache POI https://poi.apache.org/ 我不确定该文件到底要做什么,但是对于Microsoft Office文件,我想使用Apache POI https://poi.apache.org/

FileInputStream file = new FileInputStream(new File("test/resources/mapping.xls"));

//Get the workbook instance for XLS file 
HSSFWorkbook workbook = new HSSFWorkbook(file);

//Get first sheet from the workbook
HSSFSheet sheet = workbook.getSheetAt(0);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM