示例代码
public void poiTest(){
File file = new File("xxx\\test.xlsx") ;
InputStream input = new FileInputStream(file) ;
String fileName = file.getName() ;
/*
web接收的MultipartFile类
MultipartFile file;
InputStream input = file.getInputStream();
String fileName = file.getOriginalFilename() ;
*/
Workbook wb = fileName.endsWith("xlsx") ?
new XSSFWorkbook(input) : new HSSFWorkbook(input);
// 获得第一个表单
Sheet form = wb.getSheetAt(0);
int rows = form.getLastRowNum();
// 第二行开始读取,第一行为title文案
for (int i = 1; i <= rows; i++) {
int column = 0 ;
Row row = form.getRow(i) ;
// 空行,结束
if(row == null) break ;
// 第一列
Cell cell1 = row.getCell(column++);
// 设置为字符串类型
if (cell1 != null){
cell1.setCellType(cell1.CELL_TYPE_STRING);
System.out.println("第"+(i+1)+"行,"+
"第"+column+"列数据:"+cell1.getStringCellValue());
}
// 第二列
Cell cell2 = row.getCell(column++);
// 设置为字符串类型
if (cell2 != null){
cell2.setCellType(cell2.CELL_TYPE_STRING);
System.out.println("第"+(i+1)+"行,"+
"第"+column+"列数据:"+cell2.getStringCellValue());
}
}
}
maven
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-examples</artifactId>
<version>3.9</version>
</dependency>