我試圖將帶有CSS屬性的HTML模板轉(zhuǎn)換成電子表格。xlsx)文件。該模板包含組織的徽標(biāo)、客戶詳細(xì)信息和表格。我想按原樣轉(zhuǎn)換模板。我嘗試過一些圖書館,但它們沒有幫助。
這是我試過的代碼
const fs = require('fs');
const ExcelJS = require('exceljs');
// Create a new workbook
const workbook = new ExcelJS.Workbook();
// Read the HTML template file
const html = fs.readFileSync('invoice.html', 'utf-8');
// Create a worksheet
const worksheet = workbook.addWorksheet('Invoice');
// Set up styles
const headerStyle = {
fill: {
type: 'pattern',
pattern: 'solid',
fgColor: { argb: 'D21312' },
},
font: {
color: { argb: 'D21312' },
bold: true,
},
};
const cellStyle = {
border: {
top: { style: 'thin' },
left: { style: 'thin' },
bottom: { style: 'thin' },
right: { style: 'thin' },
},
};
// Create a JSDOM instance to manipulate the HTML
const jsdom = require('jsdom');
const { JSDOM } = jsdom;
const dom = new JSDOM(html);
const document = dom.window.document;
// Add the image to the worksheet
const imageFilePath = 'logo-dark.png';
const imageId = workbook.addImage({
filename: imageFilePath,
extension: 'png',
});
worksheet.addImage(imageId, {
tl: { col: 1, row: 1 },
ext: { width: 200, height: 200 },
});
// Extract the table data
const table = document.querySelector('table');
const rows = table.querySelectorAll('tr');
// Iterate through rows and cells
rows.forEach((row, rowIndex) => {
const cells = row.querySelectorAll('td');
cells.forEach((cell, cellIndex) => {
const cellValue = cell.textContent.trim();
// Set cell values and styles
const excelCell = worksheet.getCell(rowIndex + 2, cellIndex + 1);
excelCell.value = cellValue;
excelCell.border = cellStyle.border;
if (rowIndex === 0) {
excelCell.fill = headerStyle.fill;
excelCell.font = headerStyle.font;
}
});
});
// Save the workbook to a file
workbook.xlsx.writeFile('invoice.xlsx')
.then(() => {
console.log('Invoice converted to Excel successfully!');
})
.catch((error) => {
console.error('Error converting invoice to Excel:', error);
});
這是html代碼
<!DOCTYPE html>
<html>
<head>
<title>HTML Table Example</title>
<style>
table {
border-collapse: collapse;
width: 100%;
}
th,
td {
border: 1px solid rgb(243, 9, 9);
padding: 8px;
text-align: left;
}
th {
background-color: #f2f2f2;
}
.logo {
text-align: center;
}
.logo img {
max-width: 200px;
}
</style>
</head>
<body>
<table>
<thead>
<tr>
<th>Header 1</th>
<th>Header 2</th>
<th>Header 3</th>
</tr>
</thead>
<tbody>
<tr>
<td><img src="logo-dark.png" alt="Logo" /></td>
<td>Data 1-2</td>
<td>Data 1-3</td>
</tr>
<tr>
<td>Data 2-1</td>
<td>Data 2-2</td>
<td>Data 2-3</td>
</tr>
<tr>
<td>Data 3-1</td>
<td>Data 3-2</td>
<td>Data 3-3</td>
</tr>
</tbody>
</table>
</body>
</html>