You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Angular 4与Node.js实现JSON数据转Excel文件及下载?

Got it, let's walk through exactly how to export a JSON list to an Excel file using Angular 4 and Node.js. We'll split this into two clear parts: setting up the Node.js backend to generate and send the Excel response, and handling the download on the Angular 4 frontend.

Node.js 端:生成Excel并发送响应

First, we'll use the exceljs library (it's flexible and great for streaming large datasets) to create the Excel file from your JSON data.

  1. Install the required dependency
    Run this in your Node.js project folder:

    npm install exceljs --save
    
  2. Create the API endpoint
    Here's a complete example using Express. This endpoint will accept your JSON data (we'll use a POST request here, but you can adjust to GET if needed) and send back the Excel file as a response:

    const express = require('express');
    const ExcelJS = require('exceljs');
    const app = express();
    app.use(express.json());
    
    app.post('/export-to-excel', async (req, res) => {
      // Get your JSON data from the request body
      const jsonData = req.body.data;
    
      // Create a new workbook and add a worksheet
      const workbook = new ExcelJS.Workbook();
      const worksheet = workbook.addWorksheet('My Data');
    
      // Define column headers (adjust based on your JSON structure)
      const headers = Object.keys(jsonData[0]);
      worksheet.addRow(headers);
    
      // Populate the worksheet with JSON data
      jsonData.forEach(item => {
        const row = headers.map(header => item[header]);
        worksheet.addRow(row);
      });
    
      // Set response headers to trigger download
      res.setHeader(
        'Content-Type',
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      );
      res.setHeader(
        'Content-Disposition',
        'attachment; filename="exported-data.xlsx"'
      );
    
      // Stream the workbook to the response
      await workbook.xlsx.write(res);
      res.end();
    });
    
    app.listen(3000, () => {
      console.log('Server running on port 3000');
    });
    

    Note: If your JSON data is large, streaming the workbook (like we do here) is better than generating it in memory first—it keeps your server performant.

Angular 4 端:接收响应并触发下载

On the frontend, we'll use Angular's HttpClient to call the backend, handle the blob response, and trigger a browser download.

  1. Set up your service
    Create a service (or use an existing one) to handle the API call. Make sure to set responseType: 'blob' since we're dealing with binary data:

    import { Injectable } from '@angular/core';
    import { HttpClient, HttpHeaders } from '@angular/common/http';
    
    @Injectable()
    export class ExportService {
      private apiUrl = 'http://localhost:3000/export-to-excel';
    
      constructor(private http: HttpClient) {}
    
      exportToExcel(jsonData: any[]) {
        const headers = new HttpHeaders({ 'Content-Type': 'application/json' });
        return this.http.post(this.apiUrl, { data: jsonData }, {
          headers: headers,
          responseType: 'blob' as 'json' // Required for Angular 4 to handle blob correctly
        });
      }
    }
    
  2. Handle the download in your component
    Call the service method, then process the blob to create a downloadable file:

    import { Component } from '@angular/core';
    import { ExportService } from './export.service';
    
    @Component({
      selector: 'app-root',
      template: '<button (click)="downloadExcel()">Download Excel</button>'
    })
    export class AppComponent {
      // Sample JSON data (replace with your actual data)
      sampleData = [
        { id: 1, name: 'John Doe', email: 'john@example.com' },
        { id: 2, name: 'Jane Smith', email: 'jane@example.com' }
      ];
    
      constructor(private exportService: ExportService) {}
    
      downloadExcel() {
        this.exportService.exportToExcel(this.sampleData).subscribe(blob => {
          // Create a URL for the blob
          const url = window.URL.createObjectURL(blob);
          // Create an anchor tag to trigger download
          const a = document.createElement('a');
          a.href = url;
          a.download = 'exported-data.xlsx';
          // Simulate click to start download
          a.click();
          // Clean up the URL object to free memory
          window.URL.revokeObjectURL(url);
        });
      }
    }
    

    Important: Don't forget to import HttpClientModule in your AppModule to use the HttpClient service!


内容的提问来源于stack exchange,提问作者Venkata Mahesh P

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:42:24