如何用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.
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.
Install the required dependency
Run this in your Node.js project folder:npm install exceljs --saveCreate 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.
On the frontend, we'll use Angular's HttpClient to call the backend, handle the blob response, and trigger a browser download.
Set up your service
Create a service (or use an existing one) to handle the API call. Make sure to setresponseType: '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 }); } }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
HttpClientModulein yourAppModuleto use theHttpClientservice!
内容的提问来源于stack exchange,提问作者Venkata Mahesh P

