用原生poi读取文件:
@RunWith(BlockJUnit4ClassRunner.class)
public class PoiReadExcel {
public String getCellStringValue(Cell cell) {
String cellValue = "";
if (cell == null) return null;//cell不编辑则获取的cell为null
switch (cell.getCellType()) {
case STRING:
cellValue = cell.getStringCellValue();
break;
case NUMERIC:
if (DateUtil.isADateFormat(ExcelNumberFormat.from(cell.getCellStyle()))) {
Date date = cell.getDateCellValue();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
cellValue = simpleDateFormat.format(date);
} else {
cellValue = String.valueOf(cell.getNumericCellValue());
}
break;
case FORMULA:
cell.setCellType(CellType.NUMERIC);
cellValue = String.valueOf(cell.getNumericCellValue());
break;
case BOOLEAN:
cellValue = String.valueOf(cell.getBooleanCellValue());
break;
case ERROR:
cellValue = String.valueOf(cell.getErrorCellValue());
break;
case BLANK:
break;
case _NONE:
break;
default:
break;
}
return cellValue;
}
@Test
public void testBaseRead() {
List<Area> areaList = new ArrayList();
try (FileInputStream fileInputStream = new FileInputStream("C:\\Users\\ljj\\Desktop\\test.xlsx");
XSSFWorkbook hssfWorkbook = new XSSFWorkbook(fileInputStream)) {
XSSFSheet sheet = hssfWorkbook.getSheetAt(0);//按照sheet索引读取
for (Row row : sheet) {
if (row.getRowNum() == 0) {
continue;
}
String areaNumber = this.getCellStringValue(row.getCell(0));
String province = this.getCellStringValue(row.getCell(1));
String city = this.getCellStringValue(row.getCell(2));
String areaStr = this.getCellStringValue(row.getCell(3));
String postCode = this.getCellStringValue(row.getCell(4));
Area area = new Area();
area.setAreaNumber(areaNumber);
area.setProvince(province);
area.setCity(city);
area.setArea(areaStr);
area.setPostCode(postCode);
areaList.add(area);
}
} catch (Exception e) {
e.printStackTrace();
}
System.err.println(JSON.toJSONString(areaList, true));
}
}
下面测试类型均已经通过:
单元格合并:读取的值只有左上角单元格值为qy006,其他都是空串(不是null)
读取单元格值和单元格的本身格式(字体颜色,字体大小,字体,背景色,字体色,对齐方式,下划线....)无关,
但是如果单元格没有值,却设置了格式,那么获取到的值不是null,是为空串。如果清除格式不进行编辑那么此cell是null。
获取有效行和有效单元格数,作为循环的边界:
row.getLastCellNum=5(不是4) (i=0;i<5;i++)
sheet.getLastRowNum=7(不是8)
中间有空行情况:
for (Row row : sheet) {//下面没有内容后,下面的行不会再循环。底层是for循环(sheet.getLastRowNum为界限)
int cellnum=row.getLastCellNum();
for (int i = 0; i < cellnum; i++) {//中间空行的row.getLastCellNum=-1;所以直接就下一行了。
String str=this.getCellStringValue(row.getCell(i));
System.err.println("str = " + str);
}
}
读取excel改进:读取所有数据,并不关心excel是横着存放的还是竖着存放的......,最后根据需求组合数据即可
package com.blog.poi.vo;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;
public class ExcelService {
/**
* 默认读取第一个sheet:并且默认从第一行开始读取
*
* @param inputStream
* @param fileName
* @return
* @throws Exception
*/
public static List<Map<Integer, String>> getListByExcel(InputStream inputStream, String fileName) throws Exception {
return getListByExcel(inputStream, fileName, 0, null, 0);
}
/**
* 根据开始行读取
*
* @param inputStream
* @param fileName
* @param beginRowNum
* @return
* @throws Exception
*/
public static List<Map<Integer, String>> getListByExcelBeginRowNum(InputStream inputStream, String fileName, Integer beginRowNum) throws Exception {
return getListByExcel(inputStream, fileName, 0, null, beginRowNum);
}
/**
* 指定sheetName和beginRowNum读取
*
* @param inputStream
* @param fileName
* @param sheetName
* @param beginRowNum
* @return
* @throws Exception
*/
public static List<Map<Integer, String>> getListByExcelSheetNameAndBeginRowNum(InputStream inputStream, String fileName, String sheetName, Integer beginRowNum) throws Exception {
return getListByExcel(inputStream, fileName, null, sheetName, beginRowNum);
}
/**
* 指定sheetIndex和beginRowNum读取
*
* @param inputStream
* @param fileName
* @param sheetIndex
* @param beginRowNum
* @return
* @throws Exception
*/
public static List<Map<Integer, String>> getListByExcelSheetIndexAndBeginRowNum(InputStream inputStream, String fileName, Integer sheetIndex, Integer beginRowNum) throws Exception {
return getListByExcel(inputStream, fileName, sheetIndex, null, beginRowNum);
}
/**
* 根据不同类型的单元格获取String类型的值
*
* @param cell
* @return
*/
private static String getCellStringValue(Cell cell) {
String cellValue = "";
if (cell == null) return null;//cell不编辑则获取的cell为null
switch (cell.getCellType()) {
case STRING:
cellValue = cell.getStringCellValue();
break;
case NUMERIC:
if (DateUtil.isADateFormat(ExcelNumberFormat.from(cell.getCellStyle()))) {
Date date = cell.getDateCellValue();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
cellValue = simpleDateFormat.format(date);
} else {
cellValue = String.valueOf(cell.getNumericCellValue());
}
break;
case FORMULA:
cellValue = cell.getCellFormula();
break;
case BOOLEAN:
cellValue = String.valueOf(cell.getBooleanCellValue());
break;
case ERROR:
cellValue = String.valueOf(cell.getErrorCellValue());
break;
case BLANK:
break;
case _NONE:
break;
default:
break;
}
return cellValue;
}
/**
* 根据版本获取不同的workbook
*
* @param inputStream
* @param fileName
* @return
* @throws Exception
*/
private static Workbook getWorkBookByExcelFile(InputStream inputStream, String fileName) throws Exception {
try {
Workbook workbook = null;
fileName = fileName.substring(fileName.lastIndexOf("."));
if (".xls".equalsIgnoreCase(fileName)) {
workbook = new HSSFWorkbook(inputStream);
} else if (".xlsx".equalsIgnoreCase(fileName)) {
workbook = new XSSFWorkbook(inputStream);
}
return workbook;
} catch (Exception e) {
throw new Exception("根据excel版本生成工作簿发生异常", e);
}
}
/**
* 解析Excel
*
* @param inputStream
* @param fileName
* @param sheetIndex
* @param sheetName
* @param beginRowNum
* @return
* @throws Exception
*/
private static List<Map<Integer, String>> getListByExcel(InputStream inputStream, String fileName, Integer sheetIndex, String sheetName, Integer beginRowNum) throws Exception {
try (Workbook workbook = getWorkBookByExcelFile(inputStream, fileName)) {
List<Map<Integer, String>> mapList = new ArrayList<>();
Sheet sheet = null;
if (StringUtils.isNotBlank(sheetName)) {
sheet = workbook.getSheet(sheetName);
} else {
sheet = workbook.getSheetAt(sheetIndex);
}
for (Row row : sheet) {
if (row.getRowNum() < beginRowNum) {
continue;
}
Map<Integer, String> map = new HashMap<>();
int cellNum = row.getLastCellNum();
for (int i = 0; i < cellNum; i++) {
String cellValue = getCellStringValue(row.getCell(i));
map.put(i, cellValue);
}
mapList.add(map);
}
return mapList;
} catch (Exception e) {
throw new Exception("获取数据list发生异常", e);
}
}
}