Location>code7788 >text

springboot-implementation of csv file export function

Popularity:38 ℃/2024-09-19 11:37:18

excel file export, will encounter a 65535 line limit, is the number of lines of data exported more than 65535 lines will be exported failed, this is the limitations of the native excel, in this case, the export format is usually changed to csv so that you can cross this limit, at the same time generated csv file with office to open the browsing effect with no difference between the opening of the excel! can be a perfect substitute.

1. Dependencies (two fewer dependencies than exporting excel)

 <!--csvExporting dependencies -->
        <dependency>
            <groupId></groupId>
            <artifactId>poi</artifactId>
            <version>4.1.1</version>
        </dependency>

        <dependency>
            <groupId></groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>4.1.1</version>
        </dependency>

2. Code

@PostMapping("/csvExport")
    @ResponseBody
    public  void csvExport(HttpServletResponse response) {
        //Table header
        List<String> headerList = ("No.", "Name");

        // Create a workbook
        Workbook workbook = new XSSFWorkbook();
        // Create worksheets
        Sheet sheet = ("Sheet1");
        // Create table header rows
        Row headerRow = (0);
        // Write to table header
        for (int i = 0; i < (); i++) {
            Cell cell = (i);
            ((i));
        }
        // Organizational data
        List<List<Object>> data = new ArrayList<>();

        List list1 = ("001","Zhang San");
        List list2 = ("002","Li Si.");
        List list3 = ("003","Wang Wu");
        List list4 = ("004","Wang Wu");
        (list1);
        (list2);
        (list3);
        (list4);

        // Write data
        for (int i = 0; i < (); i++) {
            Row row = (i + 1);
            List<Object> rowData = (i);
            for (int j = 0; j < (); j++) {
                Cell cell = (j);
                ((j).toString());
            }
        }
        //response is an HttpServeltReponse object
        (MediaType.TEXT_PLAIN_VALUE + ";charset=utf-8");
        ("Content-Disposition", "attachment;filename=");
        try {
            (());
        } catch (IOException e) {
            ();
        } finally {
            // Close the workbook and free up memory
            try {
                ();
            } catch (IOException e) {
                ();
            }
        }

    }

3、postman call

4, export effect

Source code access (free):
(1) Login-Register:/
(2) Sign in to get points
(3) Search: springboot-csvExport csv file export