首先粘贴出来excel的模板,供大家参考。
2、java 部分工具类代码
public class ExcelReader {
private String filePath;
public ExcelReader(String filePath) {
this.filePath = filePath;
}
//返回本次导入记录及导入解析方法
public List<ExcelBean> getCourseList() throws IOException {
File file = new File(this.filePath);
InputStream inputStream = new FileInputStream(file);
BufferedInputStream in = new BufferedInputStream(inputStream);
XSSFWorkbook wb = new XSSFWorkbook(in);
XSSFSheet sheet = wb.getSheetAt(0);
int productTotalCount = 0;//总处理行数
int successCount = 0;//成功数
int errorCount = 0;//失败数
int repeatCount = 0;//重复数
String errorFilePath = "";
String repeatFilePath = "";
List<ExcelBean> list = new ArrayList<ExcelBean>();
try {
for (int i = 0; i <= sheet.getLastRowNum(); i++) {
ExcelBean eb= new ExcelBean();
XSSFRow hssfRow = sheet.getRow(i + 1);
if (hssfRow == null) {
continue;
}
if(getValue(hssfRow.getCell(Short.parseShort(String.valueOf(1)))).equals("")){
break;
}
productTotalCount++;
eb.setUserName(getValue(hssfRow.getCell(Short.parseShort(String.valueOf(0)))));
eb.setPhoneNum(getValue(hssfRow.getCell(Short.parseShort(String.valueOf(1)))));
eb.setYkkAcc(getValue(hssfRow.getCell(Short.parseShort(String.valueOf(2)))));
eb.setYkkPwd(getValue(hssfRow.getCell(Short.parseShort(String.valueOf(3)))));
System.out.println("用户名:"+eb.getUserName());
System.out.println("手机号码:"+eb.getPhoneNum());
System.out.println("账号:"+eb.getYkkAcc());
System.out.println("密码:"+eb.getYkkPwd());
list.add(eb);
}
return list;
} catch (NumberFormatException e) {
e.printStackTrace();
}
return null;
}
private String getValue(XSSFCell cell) {
if (cell.getCellType() == cell.CELL_TYPE_BOOLEAN) {
return String.valueOf(cell.getBooleanCellValue());
} else if (cell.getCellType() == cell.CELL_TYPE_NUMERIC) {
//logger.debug(cell.getNumericCellValue());
BigDecimal result = new BigDecimal(cell.getNumericCellValue());
return String.valueOf(result);
} else {
return String.valueOf(cell.getStringCellValue());
}
}
/**
* 测试代码
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
ExcelReader er = new ExcelReader("E:\\test.xlsx");
er.getCourseList();
}
}
3、ExcelBean 这个是一个实体类,里面包含要从excel 里面导出的一些实体信息,大家可根据自己的需求自己来创建,我这里就不粘贴代码了
4、这里调用之后返回的一个list ,是实体的list ,list中所包含的数据就是从excel 中拿到的。
5、我在这里的操作是先把文件上传到服务器上面,然后拿到文件的地址,完了才去解析excel 的,文件上传的代码大家可参考这里:这里
这篇文章到这里就结束了,欢迎大家提出自己的意见!!共同进步