Java Excel导入导出
一、Java利用POI实现导入导出Excel表格demo
1.引入依赖
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
2.导入demo
2.1 controller层
@PostMapping("/import")
public Result userImport2(@RequestParam("file") MultipartFile file) throws Exception{
Result result=userService.userImportExcel(file);
return result;
}
2.2 service实现类层
public Result userImportExcel(MultipartFile file){
try {
InputStream inputStream = file.getInputStream();
XSSFWorkbook sheets = new XSSFWorkbook(inputStream);
XSSFSheet sheetAt = sheets.getSheetAt(0);
int firstRowNum = sheetAt.getFirstRowNum();
int lastRowNum = sheetAt.getLastRowNum();
List<User> users=new ArrayList<>();
for(int i=firstRowNum+1;i<lastRowNum+1;i++){
XSSFRow row = sheetAt.getRow(i);
if(row!=null){
User user = new User();
user.setUname(row.getCell(0).getStringCellValue());
user.setUpassword(row.getCell(1).getStringCellValue());
user.setUsex(row.getCell(2).getStringCellValue());
user.setRole(row.getCell(3).getStringCellValue());
user.setUlove((int) row.getCell(4).getNumericCellValue());
user.setUphoto(row.getCell(5).getStringCellValue());
user.setUaddress(row.getCell(6).getStringCellValue());
users.add(user);
}
}
saveBatch(users);
return Result.success();
}catch (Exception e){
e.printStackTrace();
log.info("error:{}",e);
}
return Result.error("300","导入失败");
}
public String getValue(HSSFCell cell) {
if(cell==null){
return "";
}
String cellValue= "";
try {
DecimalFormat df=new DecimalFormat("0.00");
if(cell.getCellType()== CellType.NUMERIC){
if(HSSFDateUtil.isCellDateFormatted(cell)){
cellValue=DateFormatUtils.format(cell.getDateCellValue(),"yyyy-MM-dd");
}else{
NumberFormat instance = NumberFormat.getInstance();
cellValue=instance.format(cell.getNumericCellValue()).replace(",","");
}
}else if(cell.getCellType() == CellType.STRING){
cellValue=cell.getStringCellValue();
}else if(cell.getCellType() == CellType.BOOLEAN){
cellValue= String.valueOf(cell.getBooleanCellValue());
}else if(cell.getCellType() == CellType.ERROR){
}else if(cell.getCellType() == CellType.FORMULA){
cellValue=df.format(cell.getNumericCellValue());
}else{
cellValue=null;
}
} catch (Exception e) {
e.printStackTrace();
cellValue="-1";
}
return cellValue;
}
3.导出demo
3.1 controller层
@GetMapping("/export")
public Result userExport2(HttpServletResponse response) throws Exception{
Result result=userService.userExportExcel(response);
return result;
}
3.2 service实现类
public Result userExportExcel(HttpServletResponse response) {
try {
XSSFWorkbook sheets = new XSSFWorkbook();
XSSFSheet sheet = sheets.createSheet("用户信息");
XSSFCellStyle cellStyle = sheets.createCellStyle();
cellStyle.setAlignment(HorizontalAlignment.CENTER);
XSSFRow row = sheet.createRow(0);
this.titleExcel(row,cellStyle);
List<User> list = list();
for(int i=0;i<list.size();i++){
XSSFRow rows = sheet.createRow(i+1);
User user=list.get(i);
this.titleExcelValue(user,rows,cellStyle);
}
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
String filName= URLEncoder.encode("用户信息","UTF-8");
response.setHeader("Content-Disposition","attachment;filename="+filName+".xls");
ServletOutputStream outputStream=response.getOutputStream();
sheets.write(outputStream);
outputStream.close();
sheets.close();
return Result.success();
}catch (Exception e){
e.printStackTrace();
log.info("error:{}",e);
}
return Result.error("300","导出失败");
}
public void titleExcelValue(User user, XSSFRow row,XSSFCellStyle cellStyle) {
XSSFCell cellId = row.createCell(0);
cellId.setCellValue(user.getUid());
cellId.setCellStyle(cellStyle);
XSSFCell cellUserName = row.createCell(1);
cellUserName.setCellValue(user.getUname());
cellUserName.setCellStyle(cellStyle);
XSSFCell cellPassword = row.createCell(2);
cellPassword.setCellValue(user.getUpassword());
cellPassword.setCellStyle(cellStyle);
XSSFCell cellSex = row.createCell(3);
cellSex.setCellValue(user.getUsex());
cellSex.setCellStyle(cellStyle);
XSSFCell cellRole = row.createCell(4);
cellRole.setCellValue(user.getRole());
cellRole.setCellStyle(cellStyle);
XSSFCell cellLoveValue = row.createCell(5);
cellLoveValue.setCellValue(user.getRole());
cellLoveValue.setCellStyle(cellStyle);
XSSFCell cellPhone = row.createCell(6);
cellPhone.setCellValue(user.getUphoto());
cellPhone.setCellStyle(cellStyle);
XSSFCell cellAddress = row.createCell(7);
cellAddress.setCellValue(user.getUaddress());
cellAddress.setCellStyle(cellStyle);
}
public void titleExcel(XSSFRow row,XSSFCellStyle cellStyle){
XSSFCell cellId = row.createCell(0);
cellId.setCellValue("用户ID");
cellId.setCellStyle(cellStyle);
XSSFCell cellUserName = row.createCell(1);
cellUserName.setCellValue("用户名");
cellUserName.setCellStyle(cellStyle);
XSSFCell cellPassword = row.createCell(2);
cellPassword.setCellValue("密码");
cellPassword.setCellStyle(cellStyle);
XSSFCell cellSex = row.createCell(3);
cellSex.setCellValue("性别");
cellSex.setCellStyle(cellStyle);
XSSFCell cellRole = row.createCell(4);
cellRole.setCellValue("角色");
cellRole.setCellStyle(cellStyle);
XSSFCell cellLoveValue = row.createCell(5);
cellLoveValue.setCellValue("爱心值");
cellLoveValue.setCellStyle(cellStyle);
XSSFCell cellPhone = row.createCell(6);
cellPhone.setCellValue("电话号码");
cellPhone.setCellStyle(cellStyle);
XSSFCell cellAddress = row.createCell(7);
cellAddress.setCellValue("地址");
cellAddress.setCellStyle(cellStyle);
}
二、Hutool工具类封装方法导出导入Excel
1.引入依赖
把poi封装到工具类方法里面
<!-- hutool -->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.7.20</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
2.导入demo
@PostMapping("/import")
public Result userImport(@RequestParam("file") MultipartFile file) throws Exception{
System.out.println(file.toString());
InputStream inputStream = file.getInputStream();
ExcelReader reader = ExcelUtil.getReader(inputStream);
List<List<Object>> list = reader.read(1);
List<User> users = new ArrayList<>();
for(List<Object> row : list){
User user = new User();
user.setUname(row.get(0).toString());
user.setUpassword(row.get(1).toString());
user.setUsex(row.get(2).toString());
user.setRole(row.get(3).toString());
user.setUlove(Integer.valueOf(row.get(4).toString()));
user.setUphoto(row.get(5).toString());
user.setUaddress(row.get(6).toString());
users.add(user);
}
userService.saveBatch(users);
return Result.success();
}
3.导出demo
@GetMapping("/export")
public Result userExport(HttpServletResponse response) throws Exception{
List<User> list = userService.list();
ExcelWriter writer = ExcelUtil.getWriter(true);
writer.addHeaderAlias("uname","用户名");
writer.addHeaderAlias("upassword","密码");
writer.addHeaderAlias("usex","性别");
writer.addHeaderAlias("role","角色");
writer.addHeaderAlias("ulove","爱心值");
writer.addHeaderAlias("uphoto","电话号码");
writer.addHeaderAlias("uaddress","地址");
writer.write(list,true);
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
String filName= URLEncoder.encode("用户信息","UTF-8");
response.setHeader("Content-Disposition","attachment;filename="+filName+".xls");
ServletOutputStream outputStream=response.getOutputStream();
writer.flush(outputStream,true);
outputStream.close();
writer.close();
return Result.success();
}
|