Angular 2 CSV文件下载 [英] Angular 2 CSV File Download

查看:120
本文介绍了Angular 2 CSV文件下载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的后端在springboot应用程序中,从那里我返回一个.csv文件

I have my backend in springboot application and from there i am return a .csv file

 @RequestMapping(value = "/downloadCSV")
        public void downloadCSV(HttpServletResponse response) throws IOException {
         String csvFileName = "books.csv";

            response.setContentType("text/csv");

            // creates mock data
            String headerKey = "Content-Disposition";
            String headerValue = String.format("attachment; filename=\"%s\"",
                    csvFileName);
            response.setHeader(headerKey, headerValue);

            Book book1 = new Book("Effective Java", "Java Best Practices",
                    "Joshua Bloch", "Addision-Wesley", "0321356683", "05/08/2008",
                    38);

            Book book2 = new Book("Head First Java", "Java for Beginners",
                    "Kathy Sierra & Bert Bates", "O'Reilly Media", "0321356683",
                    "02/09/2005", 30);

            Book book3 = new Book("Thinking in Java", "Java Core In-depth",
                    "Bruce Eckel", "Prentice Hall", "0131872486", "02/26/2006", 45);

            Book book4 = new Book("Java Generics and Collections",
                    "Comprehensive guide to generics and collections",
                    "Naftalin & Philip Wadler", "O'Reilly Media", "0596527756",
                    "10/24/2006", 27);

            List<Book> listBooks = Arrays.asList(book1, book2, book3, book4);

            // uses the Super CSV API to generate CSV data from the model data
            ICsvBeanWriter csvWriter = new CsvBeanWriter(response.getWriter(),
                    CsvPreference.STANDARD_PREFERENCE);

            String[] header = { "Title", "Description", "Author", "Publisher",
                    "isbn", "PublishedDate", "Price" };


            csvWriter.writeHeader(header);

            for (Book aBook : listBooks) {
                csvWriter.write(aBook, header);
            }

            csvWriter.close();
        }

当我点击浏览器csv文件中的URL时,就会下载它.

When i am hitting the URL in browser csv file is getting downloaded.

现在我正尝试从我的angular 2应用程序中访问此URL,代码如下:

Now i am trying to hit this URL from my angular 2 app , code is like this:

    exportCSV() {
            console.log('export csv called'); 
            this.csvservice.getCSVReport().subscribe(data => this.downloadFile(data)),//console.log(data),
                error => console.log('Error downloading the file.'),
                () => console.info('OK');

        }

  downloadFile(data: any) {
        let parsedResponse = data.text();
        let blob = new Blob([parsedResponse], { type: 'text/csv' });
        let url = window.URL.createObjectURL(blob);
        window.open(url);
    }

服务:

  getCSVReport() {       
        return this.http.get(this.config.importCSVApiUrl);
    }

我正在下载文件,但它类似于

I am getting the file downloaded but its like

实际上应该是Book.csv

Actually it should be Book.csv

请指导我我所缺少的东西.

Please guide me what i am missing.

推荐答案

有一种解决方法,但是您需要在页面上创建一个<a>元素.调用revokeObjectURL清除内存:

There is a workaround, but you need to create an <a> element on the page. Call revokeObjectURL to clear the memory:

downloadFile(data: any) {
    let parsedResponse = data.text();
    let blob = new Blob([parsedResponse], { type: 'text/csv' });
    let url = window.URL.createObjectURL(blob);

    if(navigator.msSaveOrOpenBlob) {
        navigator.msSaveBlob(blob, 'Book.csv');
    } else {
        let a = document.createElement('a');
        a.href = url;
        a.download = 'Book.csv';
        document.body.appendChild(a);
        a.click();        
        document.body.removeChild(a);
    }
    window.URL.revokeObjectURL(url);
}

这篇关于Angular 2 CSV文件下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆