poi excel 导入导出

/**
* Excel导入
* @param request
* @param file
* @return
* @throws Exception
*/
@RequestMapping("/test.do")
public Object test(HttpServletRequest request,@Param("file") MultipartFile file) throws Exception{
//
InputStream inputStream = file.getInputStream();
Workbook wb0 = new HSSFWorkbook(inputStream);
List<VoUserModel> voUserModels = new ArrayList<>();
//获取Excel文档中的第一个表单
Sheet sht0 = wb0.getSheetAt(0);
//对Sheet中的每一行进行迭代
for (Row r : sht0) {
//如果当前行的行号(从0开始)未达到2(第三行)则从新循环
if (r.getRowNum() < 1) {
continue;
}
VoUserModel voUser = new VoUserModel();
//excel中类型是int 但是实体类是string 要设置该列是String类型
r.getCell(0).setCellType(Cell.CELL_TYPE_STRING);
voUser.setId(r.getCell(0).getStringCellValue());
voUser.setUsername(r.getCell(1).getStringCellValue());
voUserModels.add(voUser);
}
//voUserModels插入到数据库
System.out.println(voUserModels.size());
return "";
}


/**
* excel 导出
* @param users
* @throws Exception
*/
public void excleExport(List<User> users) throws Exception{
//创建HSSFWorkbook对象
HSSFWorkbook wb = new HSSFWorkbook();
//创建HSSFSheet对象
HSSFSheet sheet = wb.createSheet("sheet1");
//创建行对象() (第一行的标题自己定义)
HSSFRow row = sheet.createRow(0);
row.createCell(0).setCellValue("编号");
row.createCell(1).setCellValue("姓名");
row.createCell(2).setCellValue("年龄");

for (int i = 0; i < users.size(); i++) {
//对象集合又多少个就要创建多少行 (+1是标题行占用了一行)
row = sheet.createRow(i+1);
User user = users.get(i);
row.createCell(0).setCellValue(user.getId());
row.createCell(1).setCellValue(user.getUsername());
row.createCell(2).setCellValue(user.getAge());
}
//输出Excel文件 ("默认一个导出地址")
FileOutputStream output=new FileOutputStream("d:/workbook.xls");
wb.write(output);
output.flush();
}


原文地址:https://www.cnblogs.com/SeaWxx/p/8434810.html