Adding HTML Rich Text inside the Cell
Contents
[
Hide
]
Aspose.Cells supports converting Microsoft Excel oriented HTML into XLS/XLSX format. It means the HTML generated by Microsoft Excel can be converted back to XLS/XLSX format using Aspose.Cells.
Similarly, if there is some simple HTML, Aspose.Cells can convert it into HTML Rich Text. Aspose.Cells provides Cell.htmlString property which can take such a simple HTML and convert it to formatted cell text.
Below code sample shows you how to add HTML rich text inside the cell. Please see the screenshot of the output Excel file.
<!DOCTYPE html>
<html>
<head>
<title>Aspose.Cells Example</title>
</head>
<body>
<h1>Aspose.Cells HTML String Example</h1>
<input type="file" id="fileInput" accept=".xls,.xlsx,.csv" />
<button id="runExample">Run Example</button>
<a id="downloadLink" style="display: none;">Download Result</a>
<div id="result"></div>
</body>
<script src="aspose.cells.js.min.js"></script>
<script type="text/javascript">
const { Workbook, SaveFormat, Worksheet, Cell } = AsposeCells;
AsposeCells.onReady({
license: "/lic/aspose.cells.enc",
fontPath: "/fonts/",
fontList: [
"arial.ttf",
"NotoSansSC-Regular.ttf"
]
}).then(() => {
console.log("Aspose.Cells initialized");
});
document.getElementById('runExample').addEventListener('click', async () => {
const fileInput = document.getElementById('fileInput');
let workbook;
// If a file is provided, open it; otherwise create a new workbook
if (fileInput.files.length) {
const file = fileInput.files[0];
const arrayBuffer = await file.arrayBuffer();
workbook = new Workbook(new Uint8Array(arrayBuffer));
} else {
workbook = new Workbook();
}
// Access the first worksheet
const worksheet = workbook.worksheets.get(0);
// Access cell A1
const cell = worksheet.cells.get("A1");
// Set HTML formatted string to the cell (converted setter -> property)
cell.htmlString = "<Font Style=\"FONT-WEIGHT: bold;FONT-STYLE: italic;TEXT-DECORATION: underline;FONT-FAMILY: Arial;FONT-SIZE: 11pt;COLOR: #ff0000;\">This is simple HTML formatted text.</Font>";
// Save the workbook to XLSX format and provide a download link
const outputData = workbook.save(SaveFormat.Xlsx);
const blob = new Blob([outputData], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
const downloadLink = document.getElementById('downloadLink');
downloadLink.href = URL.createObjectURL(blob);
downloadLink.download = 'output_out.xlsx';
downloadLink.style.display = 'block';
downloadLink.textContent = 'Download Modified Excel File';
document.getElementById('result').innerHTML = '<p style="color: green;">HTML string written to A1. Click the download link to get the modified file.</p>';
});
</script>
</html>