一、POI读Excel数据
读取内容表
导入两个依赖:
<!-- xls文件 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
<!-- xls文件 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
需要根据表格里面的对象建立实体类ExcelDataVO,并生成get和set方法。
public class ExcelDataVO {
private String name;//姓名
private Integer age;//年龄
private String location;//居住城市
private String job;//职业
}
知识点:打印日志
//打印日志
private static Logger logger = Logger.getLogger(ExcelReader.class.getName());
//两种文件名
private static final String XLS = "xls";
private static final String XLSX = "xlsx";
根据文件后缀名类型获取对应的工作簿对象:getWorkBook
/**
* 根据文件后缀名类型获取对应的工作簿对象
* @param inputStream 读取文件的输入流
* @param fileType 文件后缀名类型(xls或xlsx)
* @return 包含文件数据的工作簿对象
* @throws IOException
*/
public static Workbook getWorkBook(InputStream inputStream, String fileType) throws IOException {
Workbook workbook = null;
if (fileType.equalsIgnoreCase(XLS)){
workbook = new HSSFWorkbook(inputStream);
}else if(fileType.equalsIgnoreCase(XLSX)){
workbook = new XSSFWorkbook(inputStream);
}
return workbook;
}
将单元格内容转换为字符串: convertCellValueToString
CellType getCellType();
public enum CellType {
@Internal(
since = "POI 3.15 beta 3"
)
_NONE(-1),
NUMERIC(0),//数值
STRING(1),//字符串
FORMULA(2),//公式
BLANK(3),//空值
BOOLEAN(4),//布尔值
ERROR(5);//错误
}
.getCellType()的几种类型值
将单元格内容转换为字符串
/**
* 将单元格内容转换为字符串
* @param cell
* @return
*/
private static String convertCellValueToString(Cell cell){
if (cell == null){
return null;
}
String returnValue = null;
switch (cell.getCellType()){
case NUMERIC://数值型 0
//case CELL_TYPE_NUMERIC://数值型 0
Double doubleValue = cell.getNumericCellValue();
// 格式化科学计数法,取一位整数
DecimalFormat df = new DecimalFormat("0");
returnValue = df.format(doubleValue);
break;
case STRING://字符串型 1
//case CELL_TYPE_STRING://字符串型 1
returnValue = cell.getStringCellValue();
break;
case FORMULA://公式型 2
//case CELL_TYPE_FORMULA://公式型 2
returnValue = cell.getCellFormula();
break;
case BLANK://空值 3
//case CELL_TYPE_BLANK://空值 3
break;
case BOOLEAN://布尔型 4
//case CELL_TYPE_BOOLEAN://布尔型 4
Boolean booleanValue = cell.getBooleanCellValue();
returnValue = booleanValue.toString();
break;
case ERROR://错误 5
//case CELL_TYPE_ERROR://错误 5
break;
default:
break;
}
return returnValue;
}
Java中 DecimalFormat 用法详解:https://www.cnblogs.com/Small-sunshine/p/11648652.html
提取每一行中需要的数据,构造成为一个结果数据对象: convertRowToData
/**
* 提取每一行中需要的数据,构造成为一个结果数据对象
* 当该行中有单元格的数据为空或不合法时,忽略该行的数据
* @param row 行数据
* @return 解析后的行数据对象,行数据错误时返回null
*/
private static ExcelDataVO convertRowToData(Row row){
ExcelDataVO resultData = new ExcelDataVO();
Cell cell;
int cellNum = 0;
//获取姓名
cell = row.getCell(cellNum++);
String name = convertCellValueToString(cell);
resultData.setName(name);
//获取年龄
cell = row.getCell(cellNum++);
String ageStr = convertCellValueToString(cell);
if (null == ageStr || "".equals(ageStr)){
//年龄为空
resultData.setAge(null);
}else {
resultData.setAge(Integer.parseInt(ageStr));
}
//获取居住地
cell = row.getCell(cellNum++);
String location = convertCellValueToString(cell);
resultData.setLocation(location);
//获取职业
cell = row.getCell(cellNum++);
String job = convertCellValueToString(cell);
resultData.setJob(job);
return resultData;
}
解析Excel数据:parseExcel
/**
* 解析Excel数据
* @param workbook Excel工作簿对象
* @return 解析结果
*/
private static List<ExcelDataVO> parseExcel(Workbook workbook){
List<ExcelDataVO> resultDataList = new ArrayList<>();
//解析sheet,parse从语法上分析
for (int sheetNum = 0; sheetNum < workbook.getNumberOfSheets(); sheetNum++) {
Sheet sheet = workbook.getSheetAt(sheetNum);
// 校验sheet是否合法
if (sheet == null){
continue;
}
// 获取第一行数据
int firstRowNum = sheet.getFirstRowNum();
System.out.println("test:firstRowNum: "+firstRowNum);
Row firstRow = sheet.getRow(firstRowNum);
System.out.println(firstRow);
if (null == firstRow){
logger.warning("解析Excel失败,在第一行没有读取到任何数据!");
}
//解析第一行数据
// 解析每一行的数据,构造数据对象
//getPhysicalNumberOfRows()获取的是物理行数,也就是不包括那些空行(隔行)的情况。
//getLastRowNum()获取的是最后一行的编号(编号从0开始)。
int rowStart = firstRowNum + 1;
int rowEnd = sheet.getPhysicalNumberOfRows();
for (int rowNum = rowStart; rowNum < rowEnd; rowNum++) {
Row row = sheet.getRow(rowNum);
if(null == row){
continue;
}
ExcelDataVO resultData = convertRowToData(row);
if (null == resultData){
logger.warning("第 " + row.getRowNum() + "行数据不合法,已忽略!");
continue;
}
resultDataList.add(resultData);
}
}
return resultDataList;
}
读取Excel文件内容readExcel
/**
* 读取Excel文件内容
* @param fileName 要读取的Excel文件所在路径
* @return 读取结果列表,读取失败时返回null
*/
public static List<ExcelDataVO> readExcel(String fileName){
Workbook workbook = null;
FileInputStream inputStream = null;
try {
// 获取Excel后缀名
String fileType = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
// 获取Excel文件
File excelFile = new File(fileName);
if (!excelFile.exists()){
logger.warning("指定的Excel文件不存在!");
return null;
}
// 获取Excel工作簿
inputStream = new FileInputStream(excelFile);
workbook = getWorkBook(inputStream, fileType);
// 读取excel中的数据
List<ExcelDataVO> resultDataList = parseExcel(workbook);
return resultDataList;
} catch (Exception e) {
logger.warning("解析Excel失败,文件名:" + fileName + " 错误信息:" + e.getMessage());
return null;
} finally {
try {
if (null != workbook){
workbook.close();
}
if (null != inputStream){
inputStream.close();
}
} catch (Exception e) {
logger.warning("关闭数据流出错!错误信息:" + e.getMessage());
return null;
}
}
}
We are family
- 德意 2020.09.08
有你的每一天,都非常的充实,每一天都充满着期待,我们分享彼此的故事,彼此云学习、云上班、云看夕阳落下……是那么的舒适愉悦
- Excel文档结构:一个Excel文档包含了多个数据表;一个数据表包含了多个行,一行中有多个单元格,我们将数据写入到单元格中。
/**
* 1、创建一个Excel表格
*/
public static void creatExcel() throws IOException {
//生成文档对象
HSSFWorkbook hssfWorkbook = new HSSFWorkbook();
//指定文档写出的路径
File file = new File("E://java//sany//poi//poiExcel.xls");
//写出对象到指定的路径
hssfWorkbook.write(file);
}
private static void writeExcelData() throws IOException {
HSSFWorkbook hssfWorkbook = new HSSFWorkbook();
HSSFSheet sheet = hssfWorkbook.createSheet("学生成绩表");
//写表头
HSSFRow row = sheet.createRow(0);
for (int i = 0; i < header.length; i++) {
HSSFCell cell = row.createCell(i);
cell.setCellValue(header[i]);
}
//写表中数据+data.length+"||"+data[0].length
for (int i = 0; i < data.length; i++) {
HSSFRow row1 = sheet.createRow(i+1);
for (int j = 0; j < data[0].length; j++) {
/**
* 进行处理,data第一个数据为字符串,后面的均为数字
*/
if (j == 0){
HSSFCell cell1 = row1.createCell(j);
cell1.setCellValue(data[i][j]);
}else {
HSSFCell cell1 = row1.createCell(j);
// cell1.setCellValue(Integer.valueOf(data[i][j]));
// Integer.parseInt(data[i][j]);
cell1.setCellValue(Double.parseDouble(data[i][j]));
}
}
}
File file = new File("E://java//sany//poi//poiExcel.xls");
hssfWorkbook.write(file);
hssfWorkbook.close();
}
夏雨雪时光
夏雨雪时光