Java: read content in excel file
1. Introducing dependencies
Note: jxl only supports reading .xls files, and reading .xlsx will report an error!
Introduce jxl dependencies in pom.xml
<dependency>
<groupId>net.sourceforge.jexcelapi</groupId>
<artifactId>jxl</artifactId>
<version>2.6.12</version>
</dependency>
2. Import work class
import jxl.Workbook; //java读取excel表使用的类
import jxl.Sheet; //java读取的工作铺的类
3. Read excel content
public void readExcel() throws Exception {
//根据文件位置找到需要读取的excel文件
File Inputfile = new File("E:\\readExcel\\needRead.xls");
//根据路径生成 FileInputStream字节流
FileInputStream fileInputStream = new FileInputStream(Inputfile);
//将FileInputStream转换为Workbook
Workbook workbook = Workbook.getWorkbook(fileInputStream);
// 默认获取第一张工作表,可以自定义
Sheet sheet = workbook.getSheet(0);
// 循环获取每一行数据 因为默认第一行为标题行,我们可以从 1 开始循环,如果没有标题行,i从 0 开始
// sheet.getRows() 获取总行数
for (int i = 1; i < sheet.getRows(); i++) {
// 获取第一列的第 i 行信息 sheet.getCell(列,行),下标从0开始
String content1 = sheet.getCell(0, i).getContents();
// 获取第二列的第 i 行信息
String content2 = sheet.getCell(1,i).getContents();
//后面根据需要以此类推
}
}
For the poi dependency instructions, usage methods and more details that support reading xlsx files, please refer to:
The way Java reads excel, an article to understand (detailed)