1、引入依赖
<!-- 导出excel -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.0.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.0.0</version>
</dependency>
<!-- lang3 工具包 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.10</version>
</dependency>
2、java代码
package com.cwzy.controller;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
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.xssf.usermodel.XSSFWorkbook;
public class ExcelController {
public static String doMethod(){
Workbook workbook = null;
// File file = new File("C:\\Users\\admin1\\Desktop\\123.xls");
File file = new File("C:\\Users\\admin1\\Desktop\\data.xlsx");
try {
InputStream inputStream = new FileInputStream(file);
String absolutePath = file.getAbsolutePath();
//通过文件类型解析不同文件
if(absolutePath.toLowerCase().endsWith(".xls")){
workbook = new HSSFWorkbook(inputStream);
}else if(absolutePath.toLowerCase().endsWith(".xlsx")){
workbook = new XSSFWorkbook(inputStream);
}else{
return "文件格式错误";
}
//获得 sheet表
Sheet sheet = workbook.getSheetAt(0);
int lastRowNum = sheet.getLastRowNum();
for (int i = 0; i <= lastRowNum; i++) {
//每一行
Row row = sheet.getRow(i);
if(row!=null){
int rowNum = row.getRowNum();
StringBuffer str = new StringBuffer();
for (int j = 0; j <= rowNum; j++) {
//每一个块
Cell cell = row.getCell(j);
if(cell!=null){
String cellValue = getCellValue(cell);
str.append(cellValue+"--");
}
}
String check = str.toString().replace("--", "");
if(StringUtils.isNotEmpty(check)){
System.out.println(str.toString());
}
}
}
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
workbook.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
return "ok";
}
//将每一个数据转为Stirng
public static String getCellValue(Cell cell){
cell.setCellType(CellType.STRING);
return String.valueOf(cell.getRichStringCellValue().getString());
}
public static void main(String[] args) {
doMethod();
}
}
本文提供了一个使用Java进行Excel文件(.xls 和 .xlsx)读取的示例代码,介绍了如何利用Apache POI库解析Excel表格,并展示了如何遍历工作表、行和单元格,获取并打印单元格的内容。
3844

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



