Cách Tùy Chỉnh Excel Để Hiển Thị Hình Ảnh Trong C#
Cách Tùy Chỉnh Excel Để Hiển Thị Hình Ảnh Trong C#
Khi xuất sổ làm việc Excel hoặc chuyển sang hình ảnh, bạn thường cần kiểm soát chính xác về cách nội dung trông như thế nào. Cho dù là để in, trình bày hay tích hợp, bài viết này cho thấy cách tùy chỉnh rendering hình ảnh bằng cách sử dụng Aspose.Cells for .NET.
Tại sao Customize Rendering?
- Tăng độ rõ ràng và độ phân giải của hình ảnh
- Hiển thị hoặc ẩn các đường dây, công thức, hoặc tiêu đề
- Tùy chỉnh bố trí và kích thước theo yêu cầu tài liệu
- Tùy chỉnh nền minh bạch hoặc biên giới
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 và sổ làm việc
Workbook workbook = new Workbook("Template.xlsx");
Worksheet worksheet = workbook.Worksheets["Sheet1"];
Bước 3: Thiết lập các tùy chọn Rendering nâng cao
ImageOrPrintOptions options = new ImageOrPrintOptions
{
ImageType = ImageType.Png,
HorizontalResolution = 300,
VerticalResolution = 300,
PrintWithStatusDialog = false,
Transparent = false,
OnePagePerSheet = true
};
Bước 4: Tạo các đường dây và đường dây (tùy chọn)
// Show gridlines in the output
options.ShowGridLines = true;
// Render row/column headings
options.ShowRowColumnHeaders = true;
Bước 5: Tùy chỉnh cài đặt trang
// Set to render entire sheet as a single page
options.AllColumnsInOnePagePerSheet = true;
options.AllRowsInOnePagePerSheet = true;
Bước 6: Chuyển sang hình ảnh với SheetRender
SheetRender renderer = new SheetRender(worksheet, options);
renderer.ToImage(0, "custom_output.png");
Bước 7: Lưu và Kiểm tra kết quả
Đảm bảo rằng hình ảnh kết quả phản ánh bố trí tùy chỉnh và lựa chọn thị giác của bạn.
Mẫu mã đầy đủ
using System;
using Aspose.Cells;
class Program
{
static void Main()
{
// Load Excel file
Workbook workbook = new Workbook("Template.xlsx");
Worksheet worksheet = workbook.Worksheets["Sheet1"];
// Set up advanced rendering options
ImageOrPrintOptions options = new ImageOrPrintOptions
{
ImageType = ImageType.Png,
HorizontalResolution = 300,
VerticalResolution = 300,
PrintWithStatusDialog = false,
Transparent = false,
OnePagePerSheet = true,
ShowGridLines = true,
ShowRowColumnHeaders = true,
AllColumnsInOnePagePerSheet = true,
AllRowsInOnePagePerSheet = true
};
// Render to image
SheetRender renderer = new SheetRender(worksheet, options);
renderer.ToImage(0, "custom_output.png");
Console.WriteLine("Custom-rendered worksheet saved as image.");
}
}
Lời khuyên để kiểm soát tốt hơn
thiết lập | Mô tả |
---|---|
ImageType | Chọn PNG, JPEG, BMP, hoặc TIFF |
Transparent | Thiết lập đúng cho nền minh bạch |
SmoothingMode | Cải thiện hình ảnh bằng cách sử dụng anti-aliasing |
ShowFormulas | Hiển thị công thức thay vì các giá trị được tính toán |
ChartImageWidth / ChartImageHeight | Thiết lập kích cỡ output cho biểu đồ |