java 数据 excel模板_java后台读取excel模板数据

该博客介绍如何使用Apache POI库在Java中读取不同版本的Excel文件(.xls和.xlsx),从指定行开始,提取数据字段,处理各种数据类型,并返回JSON对象列表。重点在于处理单元格数据并格式化输出。
摘要由CSDN通过智能技术生成

/*** 读取EXCEL模板数据

*

*@paramexcelFilePath excel文件路径

*@paramdataRowNum 开始读取数据的行数

*@paramkeyRowNum 数据字段所在行数

*@return*@throwsIOException*/

public static List readExcelData(String excelFilePath, int dataRowNum, intkeyRowNum)throwsIOException {if (excelFilePath.endsWith(".xls"))

version=version2003;else if (excelFilePath.endsWith(".xlsx"))

version=version2007;

InputStream stream= null;if (version ==version2003) {

stream= newFileInputStream(excelFilePath);

wb= (Workbook) newHSSFWorkbook(stream);

stream.close();

}else if (version ==version2007) {

wb= (Workbook) newXSSFWorkbook(excelFilePath);

}

sheet= wb.getSheetAt(0);//行数(从0开始,相当于最后一行的索引),列数

int count_row =sheet.getLastRowNum();int count_cell =sheet.getRow(keyRowNum).getPhysicalNumberOfCells();

List list =FastList.newInstance();

JSONObject count= newJSONObject();for (int i = 0; i < count_row; i++) {

JSONObject map= newJSONObject();for (int j = 0; j < count_cell; j++) {

row= sheet.getRow(i +dataRowNum);if(isRowEmpty(row)) {continue;

}if (null !=row) {

cell=((org.apache.poi.ss.usermodel.Row) row).getCell(j);

String k= "";if (null !=cell) {int type = cell.getCellType(); //得到单元格数据类型

switch (type) { //判断数据类型

caseCell.CELL_TYPE_BLANK:

k= "";break;caseCell.CELL_TYPE_BOOLEAN:

k= cell.getBooleanCellValue() + "";break;caseCell.CELL_TYPE_ERROR:

k= cell.getErrorCellValue() + "";break;caseCell.CELL_TYPE_FORMULA:

k=cell.getCellFormula();break;caseCell.CELL_TYPE_NUMERIC:if(DateUtil.isCellDateFormatted(cell)) {

k= newDataFormatter().formatRawCellContents(

cell.getNumericCellValue(),0, "yyyy-mm-dd hh:mm:ss");//格式化日期yyyy-mm-dd hh:mm:ss

} else{

k=keepTwoDecimal(cell.getNumericCellValue());// //k = cell.getNumericCellValue() + "";// //将科学计数法类型转换为字符串///*Double double1 = new Double(k);//DecimalFormat decimalFormat = new DecimalFormat("###0");//格式化设置//k = decimalFormat.format(double1);*/// //modify by zf 20191125 使用format方法解决手机号格式问题,获取原始数据//DecimalFormat df = new DecimalFormat("0");//k = df.format(cell.getNumericCellValue());

}break;caseCell.CELL_TYPE_STRING:

k=cell.getStringCellValue();break;default:break;

}

map.put(((org.apache.poi.ss.usermodel.Row) sheet.getRow(keyRowNum)).getCell(j).getStringCellValue(), k);

}

}

}if (map != null && map.size() != 0) {

list.add(map);

}

}

cell= null;

row= null;

sheet= null;

wb= null;returnlist;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值