如何在Node.js中将JSON转为CSV并添加格式?含预定义模块咨询
Great question! Let's break this down step by step since there are a couple of important parts to your request. First, a quick answer to your module question: Node.js doesn't have a built-in module specifically for converting JSON to CSV—you'll need to use a third-party library for that. Also, critical note: plain CSV files are plain text, so they don't support formatting like row colors or styled titles. If you need those visual styles, you'll want to generate an Excel file (like .xlsx) instead, since CSV can't handle that.
Let's cover both scenarios:
1. Plain CSV File (With Custom Title, No Styling)
For a basic CSV that includes your "MONTHLY REPORT" title, the csv-writer library is lightweight and easy to work with.
Step 1: Install the library
npm install csv-writer
Step 2: Code Implementation
Here's how to take your JSON data, add the custom title, and export it as a CSV:
const createCsvWriter = require('csv-writer').createObjectCsvWriter; const fs = require('fs'); // Replace this with your actual JSON data const jsonData = [ { name: "John Doe", sales: 1200, region: "North" }, { name: "Jane Smith", sales: 1800, region: "South" }, { name: "Bob Brown", sales: 900, region: "East" } ]; // First, write the title to the file (add newlines to separate it from data) const reportTitle = "MONTHLY REPORT\n\n"; fs.writeFileSync('monthly_report.csv', reportTitle); // Set up the CSV writer to append data to the existing file const csvWriter = createCsvWriter({ path: 'monthly_report.csv', header: [ {id: 'name', title: 'NAME'}, {id: 'sales', title: 'MONTHLY SALES'}, {id: 'region', title: 'REGION'} ], append: true }); // Write the JSON data to the CSV csvWriter.writeRecords(jsonData) .then(() => console.log('CSV file with title created successfully!')) .catch(err => console.error('Error creating CSV:', err));
2. Styled Excel File (With Titles & Row Colors)
If you need formatting like row colors, bold titles, or colored headers, use exceljs—it's a powerful library that supports full Excel styling.
Step 1: Install the library
npm install exceljs
Step 2: Code Implementation
This example adds a centered, bold title, styled headers, and alternating row background colors:
const ExcelJS = require('exceljs'); // Replace this with your actual JSON data const jsonData = [ { name: "John Doe", sales: 1200, region: "North" }, { name: "Jane Smith", sales: 1800, region: "South" }, { name: "Bob Brown", sales: 900, region: "East" } ]; // Create a new workbook and worksheet const workbook = new ExcelJS.Workbook(); const worksheet = workbook.addWorksheet('Monthly Report'); // Add and style the title (merge columns A-C for a centered, full-width title) worksheet.mergeCells('A1:C1'); const titleCell = worksheet.getCell('A1'); titleCell.value = 'MONTHLY REPORT'; titleCell.font = { size: 16, bold: true }; titleCell.alignment = { horizontal: 'center' }; // Add an empty row to separate the title from headers worksheet.addRow([]); // Add and style the headers const headers = ['NAME', 'MONTHLY SALES', 'REGION']; const headerRow = worksheet.addRow(headers); headerRow.eachCell(cell => { cell.font = { bold: true }; cell.fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FFD9E1F2' } // Light blue background }; }); // Add JSON data with alternating row colors jsonData.forEach((row, index) => { const dataRow = worksheet.addRow([row.name, row.sales, row.region]); // Apply light gray background to even-indexed rows if (index % 2 === 1) { dataRow.eachCell(cell => { cell.fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FFEFEFEF' } }; }); } }); // Adjust column widths for better readability worksheet.columns.forEach(column => { column.width = column.header.length + 5; }); // Save the finished Excel file workbook.xlsx.writeFile('monthly_report.xlsx') .then(() => console.log('Styled Excel file created successfully!')) .catch(err => console.error('Error creating Excel file:', err));
Key Notes:
- CSV Limitation: Plain CSV is a text-only format—any styling you try to add (like colors) won't be recognized by spreadsheet tools. Stick to Excel formats if you need visual customization.
- Alternative Libraries: If you prefer,
json2csvworks similarly for plain CSV conversions. For Excel,xlsx(from SheetJS) is another popular option, thoughexceljshas more straightforward styling APIs.
内容的提问来源于stack exchange,提问作者Ashish Maity

