program story

angularjs를 사용하여 xls로 내보내기

inputbox 2020. 12. 29. 07:02
반응형

angularjs를 사용하여 xls로 내보내기


저는 각도 js 앱을 작업 중이며 각도 js를 사용하여 데이터를 Xls로 내 보내야하는 상황에 처했습니다. 나는 인터넷에서 내보내기 기능이나 각도 js에 대한 라이브러리를 많이 검색하여 그렇게 할 수 있거나 적어도 내보내는 방법에 대한 아이디어를 얻을 수 있습니다. 여기에 표시 할 코드 나 작업이 없습니다.

제안이 필요합니다. 제발 도와주세요.

미리 감사드립니다.

최신 정보:

객체 배열 인 데이터가 있으며 테이블의 UI에서이를 반복하고 있습니다. 내 백엔드는 node.js이고 프론트 엔드는 각도 js입니다.

내 문제는 서버의 데이터가 있고 UI에서 사용하는 경우 동일한 데이터를 사용하여 각도 js를 사용하여 Xls로 내보내는 방법입니다. 백엔드에서 다시 전화를 걸어 데이터를 추출하고 내보내고 싶지 않습니다.

기존 테이블에서 사용자는 체크 박스 (모든 행 또는 모든 행)를 선택하여 데이터를 Xls로 추출 할 수 있습니다.

node.js에서는 이름이 Excel이고 nodemodules 사이트에서 사용할 수있는 노드 모듈을 사용했습니다.

내 데이터는 다음과 같습니다.

"data": [
    {
        "Name": "ANC101",
        "Date": "10/02/2014",
        "Terms": ["samsung", "nokia": "apple"]
    },{
        "Name": "ABC102",
        "Date": "10/02/2014",
        "Terms": ["motrolla", "nokia": "iPhone"]
    }
]

angularjs 또는 angularjs 라이브러리를 사용하는 솔루션을 원합니다.


이를위한 저렴한 방법은 Angular를 사용하여를 생성하고 FileSaver.js<table>사용 하여 사용자가 다운로드 할 수 있도록 테이블을 .xls 파일로 출력하는 것입니다. Excel에서 HTML 표를 스프레드 시트로 열 수 있습니다.

<div id="exportable">
    <table width="100%">
        <thead>
            <tr>
                <th>Name</th>
                <th>Email</th>
                <th>DoB</th>
            </tr>
        </thead>
        <tbody>
            <tr ng-repeat="item in items">
                <td>{{item.name}}</td>
                <td>{{item.email}}</td>
                <td>{{item.dob | date:'MM/dd/yy'}}</td>
            </tr>
        </tbody>
    </table>
</div>

수출 전화 :

var blob = new Blob([document.getElementById('exportable').innerHTML], {
        type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"
    });
    saveAs(blob, "Report.xls");
};

데모 : http://jsfiddle.net/TheSharpieOne/XNVj3/1/

체크 박스 기능과 질문 데이터로 데모를 업데이트했습니다. 데모 : http://jsfiddle.net/TheSharpieOne/XNVj3/3/


Angular.js 데이터를 쉽게 내보낼 수 있도록 XLSX.js 라이브러리와 함께 작동 할 수있는 Alasql JavaScript 라이브러리를 사용해 볼 수 있습니다 . 다음은 exportData () 함수가있는 컨트롤러의 예입니다.

function myCtrl($scope) {
  $scope.exportData = function () {
    alasql('SELECT * INTO XLSX("john.xlsx",{headers:true}) FROM ?',[$scope.items]);
  };

  $scope.items = [{
    name: "John Smith",
    email: "j.smith@example.com",
    dob: "1985-10-10"
  }, {
    name: "Jane Smith",
    email: "jane.smith@example.com",
    dob: "1988-12-22"
  }];
}

jsFiddle 에서이 예제대한 전체 HTML 및 JavaScript 코드를 참조하십시오 .

UPDATED 셀을 채색하는 또 다른 .

또한 두 개의 라이브러리를 포함해야합니다.


비슷한 것이 필요할 때 ng-csv 및 기타 솔루션이 완전히 도움이되지 않았습니다. 내 데이터는 $ scope에 있었고 그것을 보여주는 테이블이 없었습니다. 그래서 저는 Sheet.js (xslsx.js)와 FileSaver.js를 사용하여 주어진 데이터를 Excel로 내보내는 지시문을 만들었습니다.

여기 내 솔루션이 포장되어 있습니다.

예를 들어 데이터는 다음과 같습니다.

$scope.jsonToExport = [
    {
      "col1data": "1",
      "col2data": "Fight Club",
      "col3data": "Brad Pitt"
    },
    {
      "col1data": "2",
      "col2data": "Matrix Series",
      "col3data": "Keanu Reeves"
    },
    {
      "col1data": "3",
      "col2data": "V for Vendetta",
      "col3data": "Hugo Weaving"
    }
];

컨트롤러의 지시문에 대한 배열 배열로 데이터를 준비해야했습니다.

$scope.exportData = [];
// Headers:
$scope.exportData.push(["#", "Movie", "Actor"]);
// Data:
angular.forEach($scope.jsonToExport, function(value, key) {
  $scope.exportData.push([value.col1data, value.col2data, value.col3data]);
});

마지막으로 내 템플릿에 지시문을 추가합니다. 버튼이 표시됩니다. ( 바이올린 참조 ).

<div excel-export export-data="exportData" file-name="{{fileName}}"></div>

ng-grid에 데이터를로드하는 경우 CSV 내보내기 플러그인을 사용할 수 있습니다. 플러그인은 href 태그 안에 csv로 그리드 데이터가있는 버튼을 생성합니다.

http://angular-ui.github.io/ng-grid/

https://github.com/angular-ui/ng-grid/blob/2.x/plugins/ng-grid-csv-export.js

라이브러리 이름이 변경 될 때 링크 업데이트 :

Github 링크 : https://github.com/angular-ui/ui-grid

도서관 페이지 : http://ui-grid.info/

csv 내보내기에 대한 문서 : http://ui-grid.info/docs/#/tutorial/206_exporting_data


한 가지 시작점은이 지시문 (ng-csv)을 사용하는 것입니다. 파일을 csv로 다운로드하면 Excel에서 이해할 수 있습니다.

http://ngmodules.org/modules/ng-csv

이 코드를 수정할 수 있습니다 (업데이트 된 링크).

http://jsfiddle.net/Sourabh_/5ups6z84/2/

XMLSS처럼 보이지만 (파일을 열기로 선택하면 파일이 올바르게 열리도록 파일을 열기 전에 경고합니다)

var tableToExcel = (function() {

  var uri = 'data:application/vnd.ms-excel;base64,'
, template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>'
, base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) }
, format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) }

  return function(table, name) {
    if (!table.nodeType) table = document.getElementById(table)
    var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML}
    window.location.href = uri + base64(format(template, ctx))
  }
})()

사용자 정의 된 파일 이름으로 아래에서 시도하십시오.

$scope.exportData= function(){                  
    var uri = 'data:application/vnd.ms-excel;base64,'
          , template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>'
          , base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) }
          , format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) }

          var table = document.getElementById("searchResult");
          var filters = $('.ng-table-filters').remove();
          var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML};
          $('.ng-table-sort-header').after(filters) ;          
          var url = uri + base64(format(template, ctx));
          var a = document.createElement('a');
          a.href = url;
          a.download = 'Exported_Table.xls';
          a.click();        
};

$scope.ExportExcel= function () { //function define in html tag                          

                        //export to excel file
                        var tab_text = '<table border="1px" style="font-size:20px" ">';
                        var textRange;
                        var j = 0;
                        var tab = document.getElementById('TableExcel'); // id of table
                        var lines = tab.rows.length;

                        // the first headline of the table
                        if (lines > 0) {
                            tab_text = tab_text + '<tr bgcolor="#DFDFDF">' + tab.rows[0].innerHTML + '</tr>';
                        }

                        // table data lines, loop starting from 1
                        for (j = 1 ; j < lines; j++) {
                            tab_text = tab_text + "<tr>" + tab.rows[j].innerHTML + "</tr>";                                
                        }

                        tab_text = tab_text + "</table>";
                        tab_text = tab_text.replace(/<A[^>]*>|<\/A>/g, "");          //remove if u want links in your table
                        tab_text = tab_text.replace(/<img[^>]*>/gi, "");             // remove if u want images in your table
                        tab_text = tab_text.replace(/<input[^>]*>|<\/input>/gi, ""); // reomves input params

                        // console.log(tab_text); // aktivate so see the result (press F12 in browser)               
                        var fileName = 'report.xls'                            
                        var exceldata = new Blob([tab_text], { type: "application/vnd.ms-excel;charset=utf-8" }) 

                        if (window.navigator.msSaveBlob) { // IE 10+
                            window.navigator.msSaveOrOpenBlob(exceldata, fileName);
                            //$scope.DataNullEventDetails = true;
                        } else {
                            var link = document.createElement('a'); //create link download file
                            link.href = window.URL.createObjectURL(exceldata); // set url for link download
                            link.setAttribute('download', fileName); //set attribute for link created
                            document.body.appendChild(link);
                            link.click();
                            document.body.removeChild(link);
                        }

                    }

        //html of button 


이 문제가 발생하여 HTML 테이블을 CSV 파일로 내보내는 도구를 만들었습니다. FileSaver.js에서 내가 가진 문제는이 도구가 html 형식으로 테이블을 잡는다는 것입니다. 이것이 일부 사람들이 Excel 또는 Google에서 파일을 열 수없는 이유입니다. js 파일을 내 보낸 다음 함수를 호출하기 만하면됩니다. 누군가 동일한 문제가있는 경우 이것은 github URL https://github.com/snake404/tableToCSV 입니다.


We need a JSON file which we need to export in the controller of angularjs and we should be able to call from the HTML file. We will look at both. But before we start, we need to first add two files in our angular library. Those two files are json-export-excel.js and filesaver.js. Moreover, we need to include the dependency in the angular module. So the first two steps can be summarised as follows -

1) Add json-export.js and filesaver.js in your angular library.

2) Include the dependency of ngJsonExportExcel in your angular module.

      var myapp = angular.module('myapp', ['ngJsonExportExcel'])

Now that we have included the necessary files we can move on to the changes which need to be made in the HTML file and the controller. We assume that a json is being created on the controller either manually or by making a call to the backend.

HTML :

Current Page as Excel
All Pages as Excel 

In the application I worked, I brought paginated results from the backend. Therefore, I had two options for exporting to excel. One for the current page and one for all data. Once the user selects an option, a call goes to the controller which prepares a json (list). Each object in the list forms a row in the excel.

Read more at - https://www.oodlestechnologies.com/blogs/Export-to-excel-using-AngularJS

ReferenceURL : https://stackoverflow.com/questions/21680768/export-to-xls-using-angularjs

반응형