1.下载POI
打开网站http://poi.apache.org/download.html,选择版本下载。


2.解压完成后 ,把解压出来的所有的xx.jar都放在新的文件夹,然后右键你的eclipse工程> Build path > Configure build path > 点击lib > Add external jar,新建文件夹内所有的xxx.jar都选中。还有lib以及ooxml_lib文件里的jar包

3. test-data.xlsx文件
桌面新建一个test-data.xlsx,然后输入如下内容,并且把表格放到eclipse项目新建的文件夹File中。
下图源代码文件地址:源码地址
package ceshi;
import java.io.File;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
public class ReadExcel {
public static void main(String[] args) {
try{
Workbook workbook = WorkbookFactory.create(new File (".\\Files\\test-data.xlsx"));
System.out.println("sheets"+workbook.getNumberOfSheets());
@SuppressWarnings("resource")
Sheet sh1 = workbook.getSheetAt(0);
/*// 指定excel的路径
File src = new File(".\\Files\\test-data.xlsx");
// 加载文件
FileInputStream fis = new FileInputStream(src);
// 加载workbook
@SuppressWarnings("resource")
XSSFWorkbook wb=new XSSFWorkbook(fis);
//加载sheet,这里我们只有一个sheet,默认是sheet1
XSSFSheet sh1= wb.getSheetAt(0);*/
for(Row row:sh1) {
int i=0;
for(Cell cell:row) {
cell.setCellType(CellType.STRING);
String value =cell.getStringCellValue();
System.out.println("value:"+ value+"");
i++;
}
System.out.println();
}
/* // 开始读取第一行第一列的数据
System.out.println(sh1.getRow(0).getCell(0).getStringCellValue());
// 读取第一行第二列内容
System.out.println(sh1.getRow(0).getCell(1).getStringCellValue());
// 读取第二行第二列内容
System.out.println(sh1.getRow(1).getCell(0).getStringCellValue());
// 读取第二行第二列内容
System.out.println(sh1.getRow(1).getCell(1).getStringCellValue());*/
// 获取实际总行数
System.out.println(sh1.getPhysicalNumberOfRows());
// 获取实际总列数
System.out.println(sh1.getPhysicalNumberOfRows());
} catch (Exception e){
System.out.println(e.getMessage());
}
}
}
4.excel填写:

5.读取结果

本文介绍如何使用Apache POI库在Eclipse环境中读取Excel文件,包括下载、配置库文件及编写Java代码实现读取Excel数据的过程。
883

被折叠的 条评论
为什么被折叠?



