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

Angular2导出带格式(加粗、颜色、列宽)的XLS文件技术咨询

Angular 2+ Export XLS with Custom Formatting (Bold Headers, Colors, Column Widths)

Hey there! I’ve dealt with exactly this requirement in Angular projects before, and the best approach to get granular control over Excel formatting (like bold headers, colored text, column widths) is combining xlsx with sheetjs-style—a maintained fork of the older xlsx-style package. Let me share a complete, working example:

Step 1: Install Dependencies

First, install the required packages:

npm install xlsx sheetjs-style --save

Step 2: Component Implementation

Here’s a full component example that handles data preparation, styling, and export:

import { Component } from '@angular/core';
import * as XLSX from 'xlsx';
import * as XLSXStyle from 'sheetjs-style';

@Component({
  selector: 'app-export-excel',
  templateUrl: './export-excel.component.html',
  styleUrls: ['./export-excel.component.css']
})
export class ExportExcelComponent {
  // Sample data to export
  sampleData = [
    { productId: 101, productName: 'Wireless Headphones', price: 99.99, inStock: true },
    { productId: 102, productName: 'Smart Watch', price: 199.99, inStock: false },
    { productId: 103, productName: 'Bluetooth Speaker', price: 49.99, inStock: true }
  ];

  exportFormattedExcel() {
    // 1. Build worksheet data: start with header row, then add data rows
    const worksheetData = [
      ['Product ID', 'Product Name', 'Price', 'In Stock'] // Header row
    ];

    // Map object data to array rows
    this.sampleData.forEach(item => {
      worksheetData.push([
        item.productId,
        item.productName,
        `$${item.price.toFixed(2)}`,
        item.inStock ? 'Yes' : 'No'
      ]);
    });

    // 2. Create base worksheet from array data
    const worksheet = XLSX.utils.aoa_to_sheet(worksheetData);

    // 3. Define header style: bold white text on blue background, centered
    const headerStyle = {
      font: { bold: true, color: { rgb: 'FFFFFF' } },
      fill: { fgColor: { rgb: '2E75B5' } },
      alignment: { horizontal: 'center', vertical: 'center' },
      border: {
        top: { style: 'thin' },
        bottom: { style: 'thin' },
        left: { style: 'thin' },
        right: { style: 'thin' }
      }
    };

    // Apply style to every cell in the header row (row 0)
    const range = XLSX.utils.decode_range(worksheet['!ref']);
    for (let col = range.s.c; col <= range.e.c; col++) {
      const cellRef = XLSX.utils.encode_cell({ r: 0, c: col });
      if (worksheet[cellRef]) {
        worksheet[cellRef].s = headerStyle;
      }
    }

    // 4. Set custom column widths (unit: character width)
    worksheet['!cols'] = [
      { wch: 12 }, // Product ID column
      { wch: 25 }, // Product Name column
      { wch: 10 }, // Price column
      { wch: 10 }  // In Stock column
    ];

    // 5. Create workbook and add the styled worksheet
    const workbook = XLSXStyle.utils.book_new();
    XLSXStyle.utils.book_append_sheet(workbook, worksheet, 'Product Inventory');

    // 6. Trigger file download
    XLSXStyle.writeFile(workbook, 'product-inventory.xlsx');
  }
}

Step 3: Template Button

Add a button in your component’s template to trigger the export:

<button class="btn btn-primary" (click)="exportFormattedExcel()">
  Export Formatted Excel
</button>

Key Notes & Troubleshooting

  • Use sheetjs-style instead of xlsx-style: The original xlsx-style is unmaintained, so sheetjs-style fixes compatibility issues with modern Angular versions.
  • TypeScript Type Issues: If you get type errors, add "skipLibCheck": true to your tsconfig.json under compilerOptions to skip library type checking.
  • RGB Values: All color codes are 6-character hex strings without the # prefix (e.g., white is FFFFFF, blue is 2E75B5).
  • Flexible Styling: You can extend the style object to add borders, font sizes, or text wrapping—check the sheetjs-style docs for all available style properties.

内容的提问来源于stack exchange,提问作者Dhaval Lele

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:44:12