Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

There are multiple ways to achieve this, but one possible solution is:

  1. Create a variable in the controller to store the table data, including the title and empty rows:
$scope.tableData = {
  title: "My Table",
  rows: [
    {col1: "Row 1 Column 1", col2: "Row 1 Column 2"},
    {col1: "Row 2 Column 1", col2: "Row 2 Column 2"},
    {col1: "", col2: ""}, // empty row
    {col1: "", col2: ""} // empty row
  ]
};
  1. Use a third-party library like SheetJS to export the table data to Excel. Install the library using npm:
npm install xlsx --save
  1. Create a function in the controller to export the table data:
$scope.exportToExcel = function() {
  var wb = XLSX.utils.book_new();
  var ws = XLSX.utils.json_to_sheet([$scope.tableData.title], {header:[""]}); // title row
  XLSX.utils.sheet_add_json(ws, $scope.tableData.rows, {skipHeader:true, origin:"A2"}); // table rows
  wb.Sheets["Sheet1"] = ws;
  var wbout = XLSX.write(wb, {bookType:"xlsx", type:"binary"});
  saveAs(new Blob([s2ab(wbout)],{type:"application/octet-stream"}), "mytable.xlsx"); // save as file
};
  1. Add a button or link in the HTML to call the export function:
<button ng-click="exportToExcel()">Export to Excel</button>