简体   繁体   中英

Export csv file in browser

I'm trying to export csv file from browser. So the flow is next. When i on GUI click on button export it should create csv file in backend and show it to me in browser (as downloaded). But that is not happend. When i click on button it call my method from backend it create csv file and store it to folder but it doesn't show me that file in browser.

Here is my code:

public void export(HttpServletResponse response) throws IOException {       
    try {
        // create FileWriter object with file as parameter 
        FileWriter outputfile = new FileWriter("exported.csv"); 

        // create CSVWriter object filewriter object as parameter 
        CSVWriter writer = new CSVWriter(outputfile); 

        // create a List which contains String array 
        List<String[]> data = new ArrayList<String[]>(); 
        data.add(new String[] { "Name", "Class", "Marks" }); 
        data.add(new String[] { "Aman", "10", "620" }); 
        data.add(new String[] { "Suraj", "10", "630" }); 
        writer.writeAll(data); 

        // closing writer connection 
        writer.close(); 
        response.setContentType("application/ms-excel"); // or you can use text/csv
        response.setHeader("Content-Disposition", "attachment; filename=exported.csv"); 
    } 
    catch (IOException e) { 
       e.printStackTrace(); 
    } 
}

EDIT:

angular part:

.service('ExportService', function($http) {
        this.export = function() {
            return $http.post('/data/export', { responseType: 'application/octet-stream' });
        };
    })

$scope.export = function() {
    ExportService.export()
        .success(function(data, status, headers, config) {
            var blob = new Blob([data], { type: 'application/octet-stream' });
            saveAs(blob, 'Exported  - exported.csv');
            $.growl({ message: '<br>successfully exported', title: '<b>SUCCESS</b>' }, { type: 'success' });
                })
        .error(function(data, status, headers, config) {
            $.growl({ message: '<br>Exporting failed', title: '<b>ERROR</b>' }, { type: 'danger' });
            });
    }

Does anyone know what could be the problem?

You never send the file to the client. You don't even have to write the data to a file on your server first. Just use an OutputStreamWriter :

public void export(HttpServletResponse response) throws IOException {
    try (CSVWriter writer = new CSVWriter(new OutputStreamWriter(response.getOutputStream(), StandardCharsets.UTF_8)) {
        response.setContentType("text/csv");
        response.setHeader("Content-Disposition", "attachment; filename=exported.csv");

        List<String[]> data = new ArrayList<String[]>();

        data.add(new String[] { "Name", "Class", "Marks" });
        data.add(new String[] { "Aman", "10", "620" });
        data.add(new String[] { "Suraj", "10", "630" });

        writer.writeAll(data);
    }
}

By the way: I replaced the try block with a try-with-resources block. This way you make sure that the close() method of the writer is always called, even if there was an exception. Additionally there is no need to catch the exception at this place, as callers of the method must handle IOException s anyways.

You are writing your data to a file called exported.csv locally on the server. This file is not sent to the client.

You should instead write the file's content to the response.getOutputStream() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM