如何在C#中将单个Excel单元格转换为图像
如何在C#中将单个Excel单元格转换为图像
有时你只需要一个单一值 - 一个价格,一个标签,一个代码 - 你想视觉地出口这个细胞. 这个教程告诉你如何隔离和将一个单一的 Excel 细胞转换为一个图像使用 Aspose.Cells for .NET。
现实世界使用案例
- 出口价格或产品显示总额
- 隔离键计为Dashboards
- 创建个别值的图像小组
步骤指南
步骤 1: 安装 Aspose.Cells 为 .NET
dotnet add package Aspose.Cells
步骤2:下载工作簿和工作表
Workbook workbook = new Workbook("KPIReport.xlsx");
Worksheet sheet = workbook.Worksheets[0];
步骤3:选择目标细胞
// Example: Cell B5
Cell cell = sheet.Cells["B5"];
步骤4:将印刷区域设置为单元格
// Print only that one cell
sheet.PageSetup.PrintArea = "B5";
步骤5:设置图像转换选项
ImageOrPrintOptions options = new ImageOrPrintOptions
{
ImageType = ImageType.Png,
OnePagePerSheet = true,
HorizontalResolution = 300,
VerticalResolution = 300
};
步骤6:使用 SheetRender 转换
SheetRender renderer = new SheetRender(sheet, options);
renderer.ToImage(0, "cell_b5_output.png");
步骤7:保存和审查输出
您将获得一个干净的 PNG 显示一个单个单元格与格式不完整。
完整的例子代码
using System;
using Aspose.Cells;
class Program
{
static void Main()
{
// Load workbook
Workbook workbook = new Workbook("KPIReport.xlsx");
// Access the worksheet and target cell
Worksheet sheet = workbook.Worksheets[0];
Cell cell = sheet.Cells["B5"];
// Set print area to that cell
sheet.PageSetup.PrintArea = "B5";
// Image export settings
ImageOrPrintOptions options = new ImageOrPrintOptions
{
ImageType = ImageType.Png,
OnePagePerSheet = true,
HorizontalResolution = 300,
VerticalResolution = 300
};
// Render and save
SheetRender renderer = new SheetRender(sheet, options);
renderer.ToImage(0, "cell_b5_output.png");
Console.WriteLine("Cell B5 exported successfully as image.");
}
}
有助的提示
提示 | 描述 |
---|---|
提高阅读能力 | 增强分辨率或字体大小 |
添加背景或边界 | 细胞格式化之前的 rendering |
Align 内容 | 使用 cell.GetStyle() 要调和或粘贴 |