Servlet implements import and export of excel

chatting part

User Contributions

image-20230504135850500

This article will implement the import and export of excel in the form of case code. The code comments are very detailed. Please read it carefully if you need it.

important point:

1. This case focuses on how to use jsp+servlet to realize the import and export of excel. The front-end page is drawn by Xiaobai casually (meaning it is ugly). There is no professional artist, mainly because there is no need to draw a good-looking, hahaha

2. The case SQL will be included in the source code, please pay attention to the source code -> db directory

Closer to home

The database is relatively simple, and two pieces of data are created after initialization

image-20230504140511634

Let's talk about the functions implemented in this issue:

1. Request http://localhost:8080/user/getList to enter the user list home page, which contains import and export buttons

2. Click Export to export all user data to the userlist.xls file

3. Modify the data in the userlist.xls file, and import the user data in the file into the database

4. View the database, including initialization data + exported data

Implement the main process:

1. Core dependencies

<!--excel相关依赖-->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>4.1.2</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>4.1.2</version>
</dependency>

2. Encapsulate Dao, use jdbc to encapsulate two methods, namely query all data and insert in batches

I won't say much about the operation of jdbc, you can refer to the article:

3. Create a Servlet exported by Excel, part of the code

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");

        List<User> userList = userDao.selectAll();
        //创建HSSFWorkbook对象(excel的文档对象)
        HSSFWorkbook wb = new HSSFWorkbook();
        //建立新的sheet对象(excel的表单)
        HSSFSheet sheet = wb.createSheet("用户数据表");
        //在sheet里创建第一行,参数为行索引(excel的行),可以是0~65535之间的任何一个
        HSSFRow row1 = sheet.createRow(0);
        //创建单元格(excel的单元格,参数为列索引,可以是0~255之间的任何一个
        HSSFCell cell = row1.createCell(0);
        //设置单元格内容
        cell.setCellValue("用户数据一览表");
        //合并单元格CellRangeAddress构造参数依次表示起始行,截至行,起始列, 截至列
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 4));
        //在sheet里创建第二行
        HSSFRow row2 = sheet.createRow(1);
        //创建单元格并设置单元格内容
        row2.createCell(0).setCellValue("用户编号");
        row2.createCell(1).setCellValue("用户名");
        row2.createCell(2).setCellValue("用户密码");
        row2.createCell(3).setCellValue("用户年龄");
        row2.createCell(4).setCellValue("创建时间");

        int rowNum = 1;
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (User user : userList) {
    
    
            //循环在sheet创建行
            HSSFRow rown = sheet.createRow(++rowNum);
            rown.createCell(0).setCellValue(user.getId());
            rown.createCell(1).setCellValue(user.getUsername());
            rown.createCell(2).setCellValue(user.getPassword());
            rown.createCell(3).setCellValue(user.getAge());
            rown.createCell(4).setCellValue(format.format(user.getCreatetime()));
        }
        //输出Excel文件
        OutputStream output = resp.getOutputStream();
        // 设置附件响应头,浏览器会进行下载
        resp.setHeader("Content-disposition", "attachment; filename=userlist.xls");
        //响应正文的MIME类型,表示Excel
        resp.setContentType("application/vnd.ms-excel");
        wb.write(output);
        output.close();
    }

The figure below shows the corresponding relationship between the code and excel, please be aware

image-20230504142002785

4. Create a Servlet imported by Excel, part of the code

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        // 设置编码字符集
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        Part file = req.getPart("file");
        // 获取源文件名
        String fileName = file.getSubmittedFileName();
        InputStream is = file.getInputStream();
        Workbook hssfWorkbook = null;
        // 判断后缀名,分别处理
        if (fileName.endsWith("xlsx")) {
    
    
            hssfWorkbook = new XSSFWorkbook(is); //Excel 2007
        } else if (fileName.endsWith("xls")) {
    
    
            hssfWorkbook = new HSSFWorkbook(is); //Excel 2003
        } else {
    
    
            resp.setContentType("text/html;charset=utf-8");
            resp.getWriter().write("文件类型暂不支持");
        }
        List<User> list = new ArrayList<User>();
        // 循环工作表Sheet
        for (int numSheet = 0; numSheet < hssfWorkbook.getNumberOfSheets(); numSheet++) {
    
    
            Sheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);
            if (hssfSheet == null) {
    
    
                continue;
            }
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            // 循环行Row,注意从第二行开始,第0行是标题,1行是表头
            for (int rowNum = 2; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
    
    
                Row hssfRow = hssfSheet.getRow(rowNum);
                if (hssfRow != null) {
    
    
                    User user = new User();
                    Cell name = hssfRow.getCell(1);
                    Cell pwd = hssfRow.getCell(2);
                    Cell age = hssfRow.getCell(3);
                    Cell createStr = hssfRow.getCell(4);
                    user.setUsername(name.toString());
                    user.setPassword(pwd.toString());
                    Double d = new Double(age.getNumericCellValue());
                    user.setAge(d.intValue());
                    try {
    
    
                        user.setCreatetime(format.parse(createStr.toString()));
                    } catch (ParseException e) {
    
    
                        e.printStackTrace();
                    }
                    list.add(user);
                }
            }
            int i = userDao.insertBatch(list);
            System.out.println(i);
            req.getRequestDispatcher("/user/getList").forward(req, resp);
        }
    }

Note that the two for loops are looping, don’t confuse them

image-20230504143441364

5. Function test

image-20230504143924977

epilogue

1. The function is realized, and Sahua is completed.

2. For SpringBoot, it is not so complicated. The agreement is greater than the configuration. It has been done for us. Interested partners can study it by themselves.

3. The way to obtain source code and notes is still the old rule, and the group files are self-collected.

4. It's not easy to make, let's go with one button and four consecutive, your support will always be my biggest motivation!

5. Java full-stack technology exchange group: 941095490, welcome to join!

Guess you like

Origin blog.csdn.net/admin_2022/article/details/130499682