• java中 Excel表实现数据导入导出


    需要引入依赖:

    <!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi</artifactId>
      <version>4.0.0</version>
    </dependency>
    
    <!-- 如果要使用 xlsx 和 流,需要引入下面这个包 -->
    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi-ooxml</artifactId>
      <version>4.0.0</version>
    </dependency>

    数据导入:

     @PostMapping("/imp")
        public String imp(@RequestPart("filePath") MultipartFile filePath) {
    
            //创建一个excel文件
            HSSFWorkbook workbook = null;
            try {
    
                workbook = new HSSFWorkbook(filePath.getInputStream());  //获取文件
                Sheet sheet = workbook.getSheetAt(0); //获取第一个工作表
    
                //循环工作表的数据
                //getLastRowNum() 获取行
                for (int i = 0; i < sheet.getLastRowNum(); i++) {
                    Row row = sheet.getRow(i + 1); //下表是从0开始的所以 把行数设置为第二行从第二行开始读
                    Cell cell = row.getCell(0); //获取第一个单元格,以此类推
                    Cell cel2 = row.getCell(1);
                    Cell cel3 = row.getCell(2);
                    Cell cel4 = row.getCell(3);
                    Cell cel5 = row.getCell(4);
    
                    //获取值
                    int id = (int) cell.getNumericCellValue();
                    String name = cel2.toString();
                    String sex = cel3.toString();
                    String education = cel4.toString();
                    int monthly = (int) cel5.getNumericCellValue();
    
                    //把值放到对象
                    Staff staff = new Staff(id, name, sex, education, monthly);
    
                    //调用mapper进行添加
                    int count = staffMapper.insert(staff);
                    if (count > 0) {
                        System.out.println("上传成功");
                    }
                }
    
            } catch (IOException e) {
                e.printStackTrace();
            }
            return "redirect:/emp";
        }

    数据导出到本地:

      //把数据导出到Excel中
        @GetMapping("/exc")
    
        public String derive(Model model, HttpSession session) {
    
            // 第一步,创建一个webbook,对应一个Excel文件
            HSSFWorkbook wb = new HSSFWorkbook();
    
            // 第二步,在webbook中添加一页,对应Excel文件中的sheet
            HSSFSheet sheet = wb.createSheet("员工表一");
    
            // 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
            HSSFRow row = sheet.createRow((int) 0);  //0代表第一行
    
            // 第四步,创建单元格,并设置值表头 设置表头居中
            HSSFCellStyle style = wb.createCellStyle();
            style.setAlignment(HorizontalAlignment.CENTER);
    
    
            HSSFCell cell = row.createCell((short) 0);
            cell.setCellValue("员工编号");
            cell.setCellStyle(style);
    
            cell = row.createCell((short) 1);
            cell.setCellValue("姓名");
            cell.setCellStyle(style);
    
            cell = row.createCell((short) 2);
            cell.setCellValue("性别");
            cell.setCellStyle(style);
    
            cell = row.createCell((short) 3);
            cell.setCellValue("学历");
            cell.setCellStyle(style);
    
            cell = row.createCell((short) 4);
            cell.setCellValue("月薪");
            cell.setCellStyle(style);
    
    
            // 第五步,写入实体数据 实际应用中这些数据从数据库得到,
            List<Staff> list = staffMapper.selectAll();
            for (int i = 0; i < list.size(); i++) {
                row = sheet.createRow((int) i + 1);
                // 第四步,创建单元格,并设置值
                row.createCell((short) 0).setCellValue(list.get(i).getId());
                row.createCell((short) 1).setCellValue(list.get(i).getName());
                row.createCell((short) 2).setCellValue(list.get(i).getSex());
                row.createCell((short) 3).setCellValue(list.get(i).getEducation());
                row.createCell((short) 4).setCellValue(list.get(i).getMonthly());
            }
            // 第六步,将文件存到指定位置
            try {
                FileOutputStream fout = new FileOutputStream("E:\aaa.xls");
                wb.write(fout);
                fout.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            session.setAttribute("add","数据导出成功");
            return "redirect:/emp";
        }

    可以结合 SpringMVC 的上传下载使用

    @Controller
    public class ExcelController {
        @Autowired
        private ExcelService excelService;
    
        @GetMapping(value = "/excel_download")
        ResponseEntity<byte[]> downloadFile() throws IOException {
            byte[] contents = excelService.exportExcel().toByteArray();
    
            HttpHeaders headers = new HttpHeaders();
            headers.setCacheControl("no-cache, no-store, must-revalidate");
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentLength(contents.length);
            headers.setContentDispositionFormData("attachment", "xxx_" + new SimpleDateFormat("yyyyMMddhhmmss").format(new Date()) + ".xls");
    
            return ResponseEntity.ok().headers(headers).body(contents);
        }
    }
  • 相关阅读:
    iframe显示高度自适应 兼容多浏览器
    Asp.Net在Global.asax中实现URL 的重写
    文件流下载 ASP.NET
    Asp.Net实现全局定时器功能
    C#中获取本机IP地址,子网掩码,网关地址
    Asp.Net缓存实例
    Google API 天气数据缓存到一个XML中
    获取服务器信息
    C# NET 中英混合字符串截断实例
    Asp.Net实现长文章分页显示功能
  • 原文地址:https://www.cnblogs.com/nongzihong/p/10006309.html
Copyright © 2020-2023  润新知