Upload from your browser, download the Excel file into the database

The data in Excel format:
Here Insert Picture Description
JSP page:

<body>
<h2>上传用户信息</h2>
<form method="post" action="<%= request.getContextPath() %>/user/excel/upload"
      enctype="multipart/form-data">
    <input type="file" name="file1">
    <input type="file" name="file2">
    <input type="text" name="username">
    <input type="submit" name="" value="上传">
</form>

<a href="<%= request.getContextPath() %>/user/excel/output">下载</a>
</body>

maven project specific process:

1, the required jar package:

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

    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi-ooxml</artifactId>
      <version>4.1.1</version>
    </dependency>

    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.4</version>
</dependency>

2, upload the configuration file parser in the spring.xml: Spring to help deal with uploaded files, but also the spring after the treatment process the object again encapsulated as objects MultipartFile

 <!--上传的文件解析器-->
    <bean id="multipartResolver"
          class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="UTF-8"></property>
        <property name="maxInMemorySize" value="10485760"></property>
    </bean>

3, upload an Excel file:

First, upload form data from the form encapsulated as objects: a text, two file file

Packaging classes:

public class FormItems {
    private String username;
    private MultipartFile file1;
    private MultipartFile file2;
    。。。
    setter、getter略
}

Controller level code:
using the Spring, the form data package automatically as a custom object (name of the form data and custom objects correspond to attribute names)

  //上传Excel文件
 @RequestMapping("/excel/upload")
 @ResponseBody
public Result doImportExcel(FormItems items) {
        InputStream inputStream=null;
        InputStream inputStream2=null;
        //仅仅输出一下上传的用户名,没有其他操作;
        System.out.println("用户名:"+items.getUsername());
        try {
        
            //得到把文件转为输出流
            inputStream = items.getFile1().getInputStream();
            inputStream2 = items.getFile2().getInputStream();
            
            //把Excel里的用户数据封装进list
            List<User> list = OperateUploadFile.saveUploadFile(inputStream);
            List<User> list2 = OperateUploadFile.saveUploadFile(inputStream2);
            
            //把list里面的user全部放到数据库
            int save = userService.save(list);
            int save2 = userService.save(list2);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream2 != null) {
                try {
                    inputStream2.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
  }

Code top: the user data in Excel encapsulated into a list of process encapsulation methods:

public static List<User> saveUploadFile(InputStream inputStream) throws IOException {
        Workbook workbook = WorkbookFactory.create(inputStream);
        Sheet sheet = workbook.getSheetAt(0);
        //拿到sheet中最后一行数据所在行:用于循环输出下标
        int lastRowNum = sheet.getLastRowNum();
        System.out.println("lastRowNum = " + lastRowNum);

        //把Excel的数据全部封装到list集合里面
        List<User> list=new ArrayList<>();
        for (int i = 1; i <=lastRowNum ; i++) {
            Row row = sheet.getRow(i);
            User user = new User();
            user.setUsername(row.getCell(1).getStringCellValue());
            user.setPassword(row.getCell(2).getStringCellValue());
            list.add(user);
        }
        return  list;
    }

4, downloading the Excel file:
the user to get all the data in the database, can be encapsulated into a Workbook object; workbook and then the object is output.

Controller level code:

@RequestMapping("/excel/output")
@ResponseBody
public void exportExcel(HttpServletResponse response) {
        //得到数据库所有的User数据
        List<User> allUser = userService.findAllUser();

        //添加Excel的标题行
        String[] title = {"ID", "USERNAME", "PASSWORD"};
        // create a new workbook
        Workbook wb = new HSSFWorkbook();
        // create a new sheetL
        Sheet s = wb.createSheet();
        // declare a row object reference
        Row r = s.createRow(0);
        // declare a cell object reference
        for (int i = 0; i < title.length; i++) {
            r.createCell(i).setCellValue(title[i]);
        }

        //添加Excel数据行
        for (int i = 0; i < allUser.size(); i++) {
            User user = allUser.get(i);
            Row row = s.createRow(i+1);
            row.createCell(0).setCellValue(user.getId());
            row.createCell(1).setCellValue(user.getUsername());
            row.createCell(2).setCellValue(user.getPassword());

        }

        // 生成文件名
        String filename = UUID.randomUUID().toString() + ".xls";
        System.out.println("filename = " + filename);
        // 处理下载
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment; filename=" + filename);
        //得到输出对象
        // response.getWriter();
        try {
            wb.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
}

End of the text and then attach the apache poi official document:
http://poi.apache.org/components/spreadsheet/

Published 14 original articles · won praise 0 · Views 321

Guess you like

Origin blog.csdn.net/qq_38205881/article/details/104194600