基于POI依赖的文件的导入导出

信息的导入导出功能

@RequestMapping("/exportXls")
    public void exportXls(HttpServletResponse response) throws Exception {
        //文件下载的响应头
        response.setHeader("Content-Disposition","attachment;filename=employee.xls");
        //直接使用poi
        //创建excel文件
        Workbook wb = employeeService.exportXls();
        //把excel的数据输出给浏览器
        wb.write(response.getOutputStream());
    }

    @RequestMapping("/importXls")
    @ResponseBody
    public JsonResult importXls(MultipartFile file) throws Exception {
        employeeService.importXls(file);
        return new JsonResult();
    }

 public Workbook exportXls() {
        //创建excel文件
        Workbook wb = new HSSFWorkbook();
        //创建sheet(一页纸)
        Sheet sheet = wb.createSheet("员工名单");
        //标题行
        Row row = sheet.createRow(0);
        //设置内容到单元格中
        row.createCell(0).setCellValue("姓名");
        row.createCell(1).setCellValue("邮箱");
        row.createCell(2).setCellValue("年龄");
        //查询员工数据
        List<Employee> employees = employeeMapper.selectAll();
        for (int i = 0; i < employees.size(); i++) {
            Employee employee = employees.get(i);
            //创建行(每个员工就是一行)
            row = sheet.createRow(i+1);
            //设置内容到单元格中
            row.createCell(0).setCellValue(employee.getName());
            row.createCell(1).setCellValue(employee.getEmail());
            row.createCell(2).setCellValue(employee.getAge());
        }
        return wb;
    }



    public void importXls(MultipartFile file) throws Exception {
        //把接收到的文件以excel的方式去读取并操作
        Workbook wb = new HSSFWorkbook(file.getInputStream());
        //读取第一页
        Sheet sheet = wb.getSheetAt(0);
        //获取行的最大索引数
        int lastRowNum = sheet.getLastRowNum();
        //从索引为1的行数开始读(忽略标题行)
        for (int i = 1; i <= lastRowNum; i++) {
            //获取行数据
            Row row = sheet.getRow(i);
            Employee employee = new Employee();
            employee.setName(row.getCell(0).getStringCellValue());
            employee.setEmail(row.getCell(1).getStringCellValue());
            //获取文本格式的单元格内容
            employee.setAge(Integer.valueOf(row.getCell(2).getStringCellValue()));
            //获取数值类型的单元格内容
            //double value = row.getCell(2).getNumericCellValue();
            //employee.setAge((int)value);
            //设置默认密码1
            employee.setPassword("1");
            //调用保存方法
            this.save(employee,null);
        }

    }

<dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>4.1.2</version>
</dependency>

你可能感兴趣的:(POI,java)