Downloading Excel file xlsx in Angularjs and WebApi

后端 未结 5 791
离开以前
离开以前 2021-01-31 11:52


I am working on a task, in which I have to download a report in xlsx format. The report file is generated successfully from server, and is received on client side as well.

相关标签:
5条回答
  • 2021-01-31 12:19

    I encountered a similar problem when writing excel using Javascript library Excel Builder. At the end, I found the reason was that a control character '\u001a' was included in data.

    The solution is to encode the control char in Excel's way as '_x001a_'.

    The way I diagnosed the problem was like this:

    .xlsx file is just a zipped xml file. You can open it with 7-zip. Inside the xl/ folder there is a file sharedString.xml containing all strings. Extract the file and open it with Notepad++. If you see any control character, then it might be the cause.

    0 讨论(0)
  • 2021-01-31 12:21

    You a just need to do one thing only that. include following js to save file locally. Download it from "https://github.com/eligrey/FileSaver.js/" your response data should be in blob type.

    I have implemented it and its working.

    function downloadfile(url,defaultFileName){
      var self = this;
        var deferred = $q.defer();
        $http.get(url, { responseType: "blob" }).then(
           function (data){
              saveAs(data.data, defaultFileName)
              deferred.resolve(defaultFileName);                    
            }, function (data) {
               var e = /* error */
                deferred.reject(e);
            });
            return deferred.promise;
    }
    
    0 讨论(0)
  • 2021-01-31 12:24

    first install these module

    import * as Excel from 'exceljs';
    import * as fs from 'file-saver';
    

    In your function write these

     const workbook = new Excel.Workbook();
      var worksheet =  workbook.addWorksheet('sheet');
      worksheet.columns = [
        { header: 'Id', key: 'id', width: 10 },
        { header: 'Name', key: 'name', width: 32 }
      ];
     var buff = workbook.xlsx.writeBuffer().then(function (data) {
        var blob = new Blob([data], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
        fs.saveAs(blob, "publications.xlsx");
      });
    

    Fs is used to access file system and download file. You can also insert img https://www.npmjs.com/package/exceljs#images

    0 讨论(0)
  • 2021-01-31 12:26

    I was facing the same error , content was in hexa format, so i added a response type as arraybuffer, problem got resolved. please see below.

    $http({
        url: '/api/sendPMOToBackendUpdate',
        method: "POST",
        headers: {'Content-type': 'application/json'},
        data: backendTsData,
        responseType: 'arraybuffer'
    }).success(function(data, status, headers){
        var file = new Blob([ data ], { type : 'application/vnd.ms-excel'});
        var defaultFileName ="TSC-"+$scope.user.name+"-"+$scope.user.ohrId+".xls";
        saveAs(file,defaultFileName);
    }).error(function(err) {
        console.log('Error: ' + err);
    });
    
    0 讨论(0)
  • 2021-01-31 12:31

    I expect your $http call is missing the response type configuration. This is the way I download office files:

    function download(url, defaultFileName) {
        var self = this;
        var deferred = $q.defer();
        $http.get(url, { responseType: "arraybuffer" }).then(
            function (data, status, headers) {
                var type = headers('Content-Type');
                var disposition = headers('Content-Disposition');
                if (disposition) {
                    var match = disposition.match(/.*filename=\"?([^;\"]+)\"?.*/);
                    if (match[1])
                        defaultFileName = match[1];
                }
                defaultFileName = defaultFileName.replace(/[<>:"\/\\|?*]+/g, '_');
                var blob = new Blob([data], { type: type });
                saveAs(blob, defaultFileName);
                deferred.resolve(defaultFileName);                    
            }, function (data, status) {
                var e = /* error */
                deferred.reject(e);
            });
        return deferred.promise;
    }
    
    0 讨论(0)
提交回复
热议问题