Cách chuyển đổi bảng tính thành hình ảnh trong C#
Xuất khẩu một bảng tính Excel duy nhất sang định dạng hình ảnh (ví dụ, PNG, JPEG) hữu ích khi tạo các bản xem trước, xuất khẩu biểu đồ, hoặc chia sẻ các hình ảnh chỉ đọc của nội dung bảng tính. hướng dẫn này cho bạn thấy cách chuyển đổi một bảng tính từ một bảng tính Excel sang một hình ảnh bằng cách sử dụng Aspose.Cells for .NET.
Sử dụng Cases
- Tạo một bản xem trước của một sổ làm việc cụ thể
- Báo cáo xuất khẩu định dạng cho email hoặc tài liệu
- Nhúng một lá đơn vào một trang web hoặc PDF
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 file Excel
Workbook workbook = new Workbook("SalesData.xlsx");
Worksheet sheet = workbook.Worksheets["Q1 Report"]; // Access specific worksheet
Bước 3: Thiết lập các tùy chọn rendering hình ảnh
ImageOrPrintOptions options = new ImageOrPrintOptions
{
ImageType = ImageType.Png,
OnePagePerSheet = true,
HorizontalResolution = 200,
VerticalResolution = 200,
PrintingPageType = PrintingPageType.Default
};
Bước 4: Tạo SheetRender Object
SheetRender renderer = new SheetRender(sheet, options);
Bước 5: Chuyển đổi mỗi trang sang một hình ảnh
for (int pageIndex = 0; pageIndex < renderer.PageCount; pageIndex++)
{
string imageName = $"worksheet_q1_page_{pageIndex + 1}.png";
renderer.ToImage(pageIndex, imageName);
}
Bước 6: Lưu hình ảnh
Mã này tự động lưu một hình ảnh cho mỗi trang in trong sổ làm việc.
Bước 7: Tăng cường tùy chọn
Bạn có thể áp dụng thêm cài đặt layout:
// Show gridlines in the output image
options.ShowGridLines = true;
// Fit all content on a single page
options.AllColumnsInOnePagePerSheet = true;
Mẫu mã đầy đủ
using System;
using Aspose.Cells;
class Program
{
static void Main()
{
// Load the Excel workbook
Workbook workbook = new Workbook("SalesData.xlsx");
// Access a specific worksheet
Worksheet sheet = workbook.Worksheets["Q1 Report"];
// Define image rendering options
ImageOrPrintOptions options = new ImageOrPrintOptions
{
ImageType = ImageType.Png,
OnePagePerSheet = true,
HorizontalResolution = 200,
VerticalResolution = 200,
PrintingPageType = PrintingPageType.Default
};
// Enable gridlines if desired
options.ShowGridLines = true;
// Render the sheet to image(s)
SheetRender renderer = new SheetRender(sheet, options);
for (int pageIndex = 0; pageIndex < renderer.PageCount; pageIndex++)
{
string imageName = $"worksheet_q1_page_{pageIndex + 1}.png";
renderer.ToImage(pageIndex, imageName);
Console.WriteLine($"Saved: {imageName}");
}
Console.WriteLine("Worksheet successfully rendered to image(s).");
}
}
Các kịch bản phổ biến & giải quyết vấn đề
vấn đề | Giải pháp |
---|---|
Cut-off nội dung | Sử dụng AllColumnsInOnePagePerSheet = true |
Sản xuất là chất lượng thấp | Tăng độ phân giải hình ảnh |
Mạng lưới mất tích | thiết lập ShowGridLines = true |