JAVA--使用Poi对excel的导入导出

第一步先在pom.xml加入jar包


	<dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-thymeleafartifactId>
        dependency>
 	
        <dependency>
            <groupId>org.mybatis.spring.bootgroupId>
            <artifactId>mybatis-spring-boot-starterartifactId>
            <version>1.1.1version>
        dependency>
       
	
 		<dependency>
            <groupId>org.apache.poigroupId>
            <artifactId>poi-ooxmlartifactId>
            <version>3.9version>
        dependency>

在mysql数据库中创一个简单的测试表
JAVA--使用Poi对excel的导入导出_第1张图片
新建一个excel文件 放些测试数据,这里只放用户名和密码,ID和时间用默认
JAVA--使用Poi对excel的导入导出_第2张图片

导入方法

  public int adduser(MultipartFile file) throws IOException {
        int count=0;
        List<Testuser> list=new ArrayList<>();
        Workbook wb=null;
        String filename=file.getOriginalFilename();
        String suffix=filename.substring(filename.lastIndexOf(".")+1);
        //把文件转换为输入流
        InputStream inputStream=file.getInputStream();
        //判断是否是xlsx后缀
        if(suffix.equals("xlsx")){
            wb=new XSSFWorkbook(inputStream);
        }else {
            wb=new HSSFWorkbook(inputStream);
        }
        //获得第一张sheet表
        Sheet sheet=wb.getSheetAt(0);
        if(sheet!=null){
            //数据是从第三行开始,所以这里从第三行开始遍历
            for (int line=2;line<=sheet.getLastRowNum();line++){
                Testuser testuser=new Testuser();
                Row row=sheet.getRow(line);
                if(row==null)
                    continue;
                //判断单元格类型是否为文本类型
                if(1 != row.getCell(0).getCellType()){
                   continue;
                }

                testuser.setUsername(row.getCell(0).getStringCellValue());
                if(1 != row.getCell(1).getCellType()){
                    continue;
                }
               testuser.setPassword(row.getCell(1).getStringCellValue());
               list.add(testuser);
            }
        }
        //在这我是用mybatis把得到的数据集合插入了数据库
        for (Testuser testuser:list){
          int i=  testuserMapper.insertSelective(testuser);
          count=count+i;
        }
        //返回的是插入了多少行
        return count;
    }

controller 测试

   @RequestMapping("/import2db")
    public Integer import2db(MultipartFile file) throws Exception {
        int count= testUserService.adduser(file);
       return count;
    }
    //返回测试页面
   @RequestMapping("/index")
    public String index(){
        return "index";
    }

页面代码 index.html


<html>
<head>
    <meta charset="UTF-8"/>
    <title>Insert title heretitle>
head>
<body>
<h1>导入EXCELh1>
<br/>
<form class="form-horizontal" id="form_table" action="/import2db" enctype="multipart/form-data" method="post">
    <button type="submit" class="btn btn-primary">导入button>
    <input class="form-input" type="file" name="file">input>
form>
body>
html>

结果:
JAVA--使用Poi对excel的导入导出_第3张图片
JAVA--使用Poi对excel的导入导出_第4张图片

JAVA--使用Poi对excel的导入导出_第5张图片


导出方法

先创建表里的测试数据
JAVA--使用Poi对excel的导入导出_第6张图片
导出的代码:

 public  void export() throws Exception{
        //指定数据存放的位置
        OutputStream outputStream = new FileOutputStream("D:\\test.xls");
        //1.创建一个工作簿
        HSSFWorkbook workbook = new HSSFWorkbook();
        //2.创建一个工作表sheet
        HSSFSheet sheet = workbook.createSheet("test");
        //List userList = userService.selectAll();
        //构造参数依次表示起始行,截至行,起始列, 截至列
        CellRangeAddress region=new CellRangeAddress(0, 0, 0, 3);
        sheet.addMergedRegion(region);

        HSSFCellStyle style=workbook.createCellStyle();
        //水平居中
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        //垂直居中
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);



        //创建第一行
        HSSFRow row1 = sheet.createRow(0);
        HSSFCell cell = row1.createCell(0);
        //设置值,这里合并单元格后相当于标题
        cell.setCellValue("人员信息表");
        //将样式添加生效
        cell.setCellStyle(style);

        //创建第二行
        HSSFRow row=sheet.createRow(1);

        //创建行首标题
        row.createCell(0).setCellValue("用户ID");
        row.createCell(1).setCellValue("用户UUID");
        row.createCell(2).setCellValue("用户名称");
        row.createCell(3).setCellValue("用户数据插入时间");

        //获得数据库中用户信息到集合中
        List<User> list=userMapper.getAllUser();
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        for (int i=0;i<list.size();i++){
            User user=list.get(i);
            //创建第i+2行,也就是i+3行
            HSSFRow row2=sheet.createRow(i+2);
            //对列赋值
            row2.createCell(0).setCellValue(user.getId());
            row2.createCell(1).setCellValue(user.getUuid());
            row2.createCell(2).setCellValue(user.getName());

            row2.createCell(3).setCellValue(simpleDateFormat.format(user.getCreatetime()));
        }



        workbook.write(outputStream);
        outputStream.close();
    }

运行测试结果:
JAVA--使用Poi对excel的导入导出_第7张图片


一个用来判断excel中行是否为空的方法
因为在sheet.getLastRowNum()这个方法获得excel表所有行时,若是某一行为空,但是样式变化了,也会算进来。所以需要一个判断该行是否为空的方法

 public static boolean isRowEmpty(Row row) {
        for (int c = row.getFirstCellNum(); c < row.getLastCellNum(); c++) {
            Cell cell = row.getCell(c);
            if (cell != null && cell.getCellType() != Cell.CELL_TYPE_BLANK){
                return false;
            }
        }
        return true;
    }

你可能感兴趣的:(JAVA基础)