javascript 如何使用angularjs将HTML表格中的数据导出到excel

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30452435/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 12:12:12  来源:igfitidea点击:

How to export data from HTML table to excel using angularjs

javascriptangularjsexport-to-excel

提问by pankaj

I want to export data in my html table to an excel sheet using angularjs on abutton click. I tried a code, but in vain.i m getting the button click event triggered though but nothing else seems to happen

我想在单击按钮时使用 angularjs 将 html 表中的数据导出到 Excel 表。我尝试了一个代码,但徒劳无功。我虽然触发了按钮点击事件,但似乎没有其他事情发生

<table class="table table-bordered table-condensed table-hover  table-striped" id="tableId">
<tr ng-repeat="mas in vm1 | orderBy:orderByField:reverseSort">
                            <td>{{::mas.contractNumber}} </td>
                            <td>{{::mas.planNumber}} </td>
                            <td>{{::mas.businessErrorMsg }} </td>
                            <td>{{::mas.systemErrorMsg}} </td>

                        </tr>
 <button class="btn btn-link" ng-click="exportToExcel('#tableId')">
                            <span class="glyphicon glyphicon-share"></span>Export to Excel
                        </button>

//controller code

//控制器代码

app.controller("ErrorDetailController", [
    "$scope", "$location", "$routeParams", "messageService", "errorService", "repositoryService", , "sharedPageService",
    function ($scope, $location, $routeParams, messageService, errorService, repositoryService,sharedPageService, **Excel, $timeout**) {
$scope.exportToExcel = function (tableId) { // ex: '#my-table'

            debugger;
            var exportHref = Excel.tableToExcel(tableId, 'sheet name');
            $timeout(function () { location.href = exportHref; }, 100); // trigger download
        }
}
]);

app.factory('Excel', function ($window) {
    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 {
        tableToExcel: function (tableId, worksheetName) {
            var table = $(tableId),
                ctx = { worksheet: worksheetName, table: table.html() },
                href = uri + base64(format(template, ctx));
            return href;
        }
    };
})

采纳答案by Hari Pachuveetil

You can use the ng-table-to-csvmodule to export HTML tables into CSV files (that can be opened in Excel).

您可以使用该ng-table-to-csv模块将 HTML 表格导出为 CSV 文件(可以在 Excel 中打开)。

As given on the README of that repo, here is the usage:

正如该 repo 的 README 所给出的,这是用法:

Getting Started / Usage

Install module via bower (or download the files from the distfolder in the repo):

shell bower install ng-table-to-csv --save

Add a reference to dist/ng-table-to-csv.jsinto your HTML pages.

Add ngTableToCsvas a dependency to your module:

js angular.module('your_app', ['ngTableToCsv']);

Add export-csvattribute directive on the tableto define a new csvobject on the scope with generate()and link()functions on them.

Options: - Use the separatorattribute to change the default comma separator into something else (like semicolon). - Use the export-csv-ignoreattribute to set the selector that will be used for prevent tr/th/tdto be stringified.

To create an Exportbutton from an anchro tag, use the generate()and link()functions mentioned above from ng-clickand ng-hrefattributes of an anchor tag.

See below:

html <a class="btn" title="Export Table" ng-click='csv.generate()' ng-href="{{ csv.link() }}" download="myTable.csv"> <i class="glyphicon glyphicon-new-window"></i> &#160;Export </a> <table class="table table-bordered" export-csv="csv" separator=";"> <!-- table contents --> </table>

入门/使用

通过 bower 安装模块(或从distrepo 中的文件夹下载文件):

shell bower install ng-table-to-csv --save

dist/ng-table-to-csv.js在 HTML 页面中添加对的引用。

添加ngTableToCsv为模块的依赖项:

js angular.module('your_app', ['ngTableToCsv']);

在 上添加export-csv属性指令以在作用域上table定义一个新 csv对象,generate()link()在其上使用函数。

选项: - 使用该separator属性将默认逗号分隔符更改为其他内容(如分号)。-使用export-csv-ignore属性设置将被用于防止选择器tr/ th/td将字符串化。

要从Exportanchro 标签创建按钮,请使用上面提到的generate()link()函数 fromng-clickng-href锚标签的属性。

见下文:

html <a class="btn" title="Export Table" ng-click='csv.generate()' ng-href="{{ csv.link() }}" download="myTable.csv"> <i class="glyphicon glyphicon-new-window"></i> &#160;Export </a> <table class="table table-bordered" export-csv="csv" separator=";"> <!-- table contents --> </table>

回答by ashish kumar

Use :

利用 :

<body>{table}</body>

instead of :

代替 :

<body><table>{table}</table></body>in template variable.

<body><table>{table}</table></body>在模板变量中。