java 读取excel中列信息
导入依赖
<!--excel下载-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.14</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.14</version>
</dependency>
java代码实现
package com.cudatec.overseas.cfg.util;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
/**
* @program:
* @description:
* @author:
* @create:
**/
public class ImportExcelUtil {
public static List<String> getUsers(String filePath) {
//excel文件
File excelFile = null;
// 输入流对象
InputStream inputStream = null;
// 单元格,最终按字符串处理
String cellStr = null;
// 返回封装数据的List
List<String> users = new ArrayList<>();
try {
excelFile = new File(filePath);
// 获取文件输入流
inputStream = new FileInputStream(excelFile);
// 创建Excel文件对象
HSSFWorkbook hssfWorkbook = new HSSFWorkbook(inputStream);
// 取出第一个工作表,索引是0
HSSFSheet sheet = hssfWorkbook.getSheetAt(0);
// 开始循环遍历行,表头不处理,从1开始
for (int i = 1; i <= sheet.getLastRowNum(); i++) {
// 获取行对象
HSSFRow row = sheet.getRow(i);
// 如果为空,不处理
if (row == null) {
continue;
}
for (int j = 0; j < row.getLastCellNum(); j++) {
// 获取单元格对象
HSSFCell cell = row.getCell(j);
// 单元格为空设置cellStr为空串
if (cell == null) {
cellStr = "";
// 对布尔值的处理
} else if (cell.getCellType() == HSSFCell.CELL_TYPE_BOOLEAN) {
cellStr = String.valueOf(cell.getBooleanCellValue());
// 对数字值的处理
} else if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
cellStr = cell.getNumericCellValue() + "";
} else {
// 其余按照字符串处理
cellStr = cell.getStringCellValue();
}
}
// 数据装入List
users.add(cellStr);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭文件流
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
for(String su :users){
System.out.println(su);
}
return users;
}
}
如果帮助到了你,麻烦关注下,谢谢!