Cách Chuyển Đổi Excel Sang HTML trong C#
Cách Chuyển Đổi Excel Sang HTML trong C#
Xuất dữ liệu Excel sang định dạng HTML là điều cần thiết khi hiển thị nội dung bảng điều khiển trong trình duyệt, mẫu email, hoặc các ứng dụng web. hướng dẫn này cho thấy làm thế nào để chuyển đổi sổ làm việc Excel sang HTML bằng cách sử dụng Aspose.Cells cho .NET.
Khi nào để sử dụng Excel để chuyển đổi HTML
- Tạo xem trước dữ liệu Excel trên các trang web
- Khả năng xem trang web dựa trên spreadsheet
- Nhúng dữ liệu bảng trong CMS hoặc blog
Hướng dẫn Step-by-Step
Bước 1: Cài đặt Aspose.Cells cho .NET
dotnet add package Aspose.Cells
Bước 2: tải sổ làm việc
Workbook workbook = new Workbook("path/to/excel.xlsx");
Bước 3: Thiết lập HTML Save Options (tùy chọn)
HtmlSaveOptions options = new HtmlSaveOptions(SaveFormat.Html);
Bước 4: Export Excel to HTML File
workbook.Save("path/to/output.html", options);
Bước 5: Lưu vào MemoryStream thay vì một tệp
using (MemoryStream outputStream = new MemoryStream())
{
workbook.Save(outputStream, SaveFormat.Html);
outputStream.Position = 0;
// Use the stream in a web response, save to disk, etc.
}
Mẫu mã đầy đủ
using System;
using System.IO;
using Aspose.Cells;
class Program
{
static void Main()
{
Workbook workbook = new Workbook("input.xlsx");
// Option 1: Save to HTML file
HtmlSaveOptions options = new HtmlSaveOptions(SaveFormat.Html);
workbook.Save("output.html", options);
// Option 2: Save to stream for web applications
using (MemoryStream stream = new MemoryStream())
{
workbook.Save(stream, SaveFormat.Html);
stream.Position = 0;
// Use the stream as needed (e.g., send in API response)
}
Console.WriteLine("Excel exported to HTML.");
}
}
Lời khuyên và thực hành tốt nhất
Lời bài hát | Mô tả |
---|---|
Sử dụng HtmlSaveOptions | Kết quả tốt cấu trúc HTML, mã hóa nhân vật, hoặc hình ảnh tích hợp |
Tiết kiệm cho Stream | hữu ích cho APIs hoặc chức năng không có máy chủ |
Bảo vệ styling | Aspose.Cells đảm bảo hầu hết các yếu tố phong cách và bố trí được giữ lại |