Aspose.Cells HTML Converter for .NET
Aspose.Cells HTML Converter for .NET enables seamless, high-fidelity conversion between Excel workbooks (XLS, XLSX, XLSM, XLTX, XLTM, XLSB) and HTML/MHTML documents. It exposes a focused API tailored for HTML export and import, ensuring quick integration into any .NET application that requires rendering or embedding spreadsheet content on the web.
Installation and Setup
To get started, add the Aspose.Cells for .NET NuGet package to your project. Refer to the detailed steps on the Installation page.
For licensing, this plugin uses metered licensing just like Aspose.Cells; see the Metered Licensing guide for configuration details.
Features and Functionalities
Supported Formats
• Excel to HTML: Convert Excel files (XLS, XLSX, XLSM, XLTX, XLTM, XLSB) into standards-compliant HTML or MHTML. • HTML to Excel: Import HTML/MHTML back into Excel workbooks for round-trip editing.
High-Fidelity Conversion
• Preserves cell formatting, merged regions, formulas (as text), images, charts, and shapes. • CSS-based styling for consistent look and feel across web pages. • Responsive HTML table output for mobile-friendly rendering.
Customizable Conversion Options
• Custom Cell Attributes: Add custom HTML attributes to cells for enhanced interactivity and data binding. • Selective Sheet Export: Export specific worksheets instead of the entire workbook. • Export Format Control: Generate complete HTML documents or fragments for embedding. • Pagination Control: Handle multi-sheet workbooks with custom navigation. • Resource Handling: Configure inline or external resources (images, fonts, CSS).
Stream-Based Processing
• Memory Stream Support: Convert directly to memory streams for in-memory processing. • Efficient I/O: Stream-based APIs minimize memory footprint. • Web Application Integration: Seamlessly output HTML to HTTP response streams.
Batch Processing and Automation
• Iterate through multiple workbooks to automate bulk HTML generation. • Event hooks for injecting custom HTML or CSS during conversion. • Thread-safe API enabling parallel processing.
Performance and Memory Optimization
• Stream-based APIs for efficient I/O. • Lazy loading of specific sheets or ranges for large workbooks. • Support for compressed HTML output (GZip) and bundling of assets.
Logging and Error Handling
• Exposes detailed diagnostics for unsupported elements or missing fonts. • Retry strategies for transient errors. • Graceful degradation to plain text rendering when needed.
Compatibility and Extensibility
• Works across .NET Framework, .NET Core, and .NET 5/6+. • Can be combined with Aspose.Cells APIs for advanced data manipulation before export. • Lightweight assembly optimized for HTML conversion tasks.
Usage Examples
Basic Conversion: Excel to HTML
The simplest way to convert an Excel file to HTML using a single line of code:
using Aspose.Cells.LowCode;
string src = "mytemplate.xlsx";
HtmlConverter.Process(src, "result\\PluginHtml1.html");
Advanced Conversion with Custom Options
Configure conversion options for more control over the HTML output:
using Aspose.Cells.LowCode;
using Aspose.Cells;
using System.IO;
using System.Text;
string src = "mytemplate.xlsx";
// Configure load options
LowCodeLoadOptions lclopts = new LowCodeLoadOptions();
lclopts.InputFile = src;
// Configure HTML save options
LowCodeHtmlSaveOptions lcsopts = new LowCodeHtmlSaveOptions();
HtmlSaveOptions htmlOpts = new HtmlSaveOptions();
// Add custom attribute to cells for data binding or JavaScript interaction
htmlOpts.CellNameAttribute = "SpecAddress";
// Export only the first worksheet (index 0)
htmlOpts.SheetSet = new Aspose.Cells.Rendering.SheetSet(new int[] { 0 });
lcsopts.HtmlOptions = htmlOpts;
// Output to memory stream for in-memory processing
MemoryStream ms = new MemoryStream();
lcsopts.OutputStream = ms;
// Perform conversion
HtmlConverter.Process(lclopts, lcsopts);
// Verify custom attribute in output
string htmlContent = Encoding.ASCII.GetString(ms.ToArray());
Console.WriteLine(htmlContent.IndexOf("SpecAddress=\"B2\"") > 0
? "Specified attribute has been output"
: "Cannot find the expected attribute");
Feature Breakdown: Custom Cell Attributes
Add custom HTML attributes to cells for enhanced web integration:
HtmlSaveOptions htmlOpts = new HtmlSaveOptions();
htmlOpts.CellNameAttribute = "data-cell"; // Cells will have data-cell="A1", data-cell="B2", etc.
Use Cases:
- JavaScript event handling on specific cells
- Data binding in web frameworks (Angular, React, Vue)
- CSS styling based on cell addresses
- Accessibility improvements with ARIA attributes
Feature Breakdown: Selective Sheet Export
Export specific worksheets to reduce HTML file size and processing time:
// Export only the first sheet (index 0)
htmlOpts.SheetSet = new Aspose.Cells.Rendering.SheetSet(new int[] { 0 });
// Export multiple specific sheets
htmlOpts.SheetSet = new Aspose.Cells.Rendering.SheetSet(new int[] { 0, 2, 4 });
Use Cases:
- Dashboard pages showing summary sheets only
- Multi-page reports with separate HTML files per sheet
- Excluding hidden or calculation sheets from web display
Feature Breakdown: Stream-Based Output
Process conversions entirely in memory without touching the file system:
MemoryStream ms = new MemoryStream();
lcsopts.OutputStream = ms;
HtmlConverter.Process(lclopts, lcsopts);
// Use the stream content
byte[] htmlBytes = ms.ToArray();
string htmlString = Encoding.UTF8.GetString(htmlBytes);
Use Cases:
- Web APIs returning HTML content directly
- Cloud functions with ephemeral storage
- Caching HTML output in memory or Redis
- Email generation with embedded Excel data
Traditional API: Full Control
For scenarios requiring maximum control, use the traditional Workbook API:
using Aspose.Cells;
// Load your source workbook
Workbook workbook = new Workbook("Book1.xlsx");
// Configure detailed options
HtmlSaveOptions saveOptions = new HtmlSaveOptions();
saveOptions.ExportGridLines = true;
saveOptions.ExportImagesAsBase64 = true;
saveOptions.PresentationPreference = true;
// Save file to HTML format
workbook.Save("out.html", saveOptions);
Tips and Best Practices
Performance Optimization
• Selective Export: Use SheetSet
to export only necessary worksheets and reduce processing time.
• Stream-Based APIs: Leverage memory streams in web applications to minimize disk I/O.
• Validate Input: Check worksheet size and complexity before conversion to avoid performance bottlenecks.
Output Quality
• Custom Attributes: Use CellNameAttribute
for better JavaScript integration and DOM manipulation.
• Resource Management: Configure inline vs. external resources based on deployment scenario.
• Fine-Tune Options: Leverage HtmlSaveOptions
to control grid lines, formulas, and image handling.
Memory Management
• Dispose Resources: Always wrap conversion operations in using
blocks to release resources promptly.
• Stream Reuse: Reset and reuse memory streams for batch conversions to reduce GC pressure.
Production Deployment
• Error Handling: Implement try-catch blocks and log conversion warnings for quality assurance. • Batch Processing: Apply producer-consumer patterns for high-volume conversions. • Caching Strategy: Cache generated HTML intelligently in dynamic web applications. • Output Verification: Validate HTML output contains expected content using string searches or HTML parsers.
Common Issues and Resolutions
Issue | Resolution |
---|---|
File not found | Verify file path accuracy and ensure proper escaping of backslashes in Windows paths |
Unsupported file format | Ensure the input format is supported by Aspose.Cells (XLS, XLSX, XLSM, XLTX, XLTM, XLSB) |
Custom attribute not appearing | Verify CellNameAttribute is set before calling Process() and check HTML output encoding |
Memory overflow | Use selective sheet export or process large files in chunks using range-based conversion |
Missing images in HTML | Configure ExportImagesAsBase64 or ensure external image paths are accessible |
API Reference Summary
Key Classes
HtmlConverter
: Static class providing simplified conversion methodsLowCodeLoadOptions
: Configuration for loading Excel filesLowCodeHtmlSaveOptions
: Configuration for HTML outputHtmlSaveOptions
: Detailed HTML conversion settingsSheetSet
: Specifies which worksheets to export
Essential Properties
CellNameAttribute
: Custom HTML attribute name for cell addressingSheetSet
: Array of worksheet indices to exportOutputStream
: Target stream for HTML outputInputFile
: Source Excel file path