JavaはExcelファイルデータを読み込み、.xlsと.xlsxを互換性がある
/**
* @param filePath
* @Description Excel
* @Throws
* @Return org.apache.poi.ss.usermodel.Workbook
* @Date 2020-07-23 18:56:29
* @Author WangKun
*/
public static Workbook readExcel(String filePath) {
if (filePath == null) {
return null;
}
String extString = filePath.substring(filePath.lastIndexOf("."));
try {
InputStream is = new FileInputStream(filePath);
if (".xls".equals(extString)) {
return new HSSFWorkbook(is);
} else if (".xlsx".equals(extString)) {
return new XSSFWorkbook(is);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* @param file
* @Description
* @Throws
* @Return void
* @Date 2020-07-23 18:57:32
* @Author WangKun
*/
public void importExcel(File file) {
Workbook wb;
Sheet sheet;
Row row;
wb = readExcel(file.getAbsolutePath());
if (wb != null) {
try {
List>> list = new ArrayList<>();
//
for (int sheetNum = 0; sheetNum < wb.getNumberOfSheets(); sheetNum++) {
//
sheet = wb.getSheetAt(sheetNum);
// List
List> sheetList = new ArrayList<>();
//
for (int rowNum = 0; rowNum <= sheet.getLastRowNum(); rowNum++) {
//
row = sheet.getRow(rowNum);
// List
List
/**
* @param cell
* @Description
* @Throws
* @Return java.lang.String
* @Date 2020-07-23 18:56:54
* @Author WangKun
*/
public static String getStringCellValue(Cell cell) {
String cellvalue;
if (cell == null) {
return "";
}
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
cellvalue = cell.getStringCellValue();
break;
case Cell.CELL_TYPE_NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = cell.getDateCellValue();
cellvalue = sdf.format(date);
} else {
cellvalue = String.valueOf(cell.getNumericCellValue());
}
break;
case Cell.CELL_TYPE_BOOLEAN:
cellvalue = String.valueOf(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_BLANK:
cellvalue = "";
break;
default:
cellvalue = "";
break;
}
return cellvalue;
}
mave構成
org.apache.xmlbeans
xmlbeans
2.6.0
org.apache.poi
poi
3.9
org.apache.poi
poi-ooxml
3.9
org.apache.poi
poi-ooxml-schemas
3.9
org.apache.commons
commons-collections4
4.1
JavaがExcelテーブルのデータストリームを読み取る一連のエラー問題の解決策について、苦労してまとめました.
参照先:https://blog.csdn.net/weixin_40295575/article/details/81354099