使用 WorkbookSetting.StreamProvider 控制外部资源

可能的使用场景

有时,您的 Excel 文件包含外部资源,例如链接图像等。Aspose.Cells 允许您使用以下命令控制这些外部资源工作簿.设置.StreamProvider这需要实施IStreamProvider界面。每当您尝试呈现包含外部资源(例如链接图像)的工作表时,IStreamProvider接口将被调用,这将使您能够对外部资源采取适当的操作。

使用 WorkbookSetting.StreamProvider 控制外部资源

下面的示例代码解释了工作簿.设置.StreamProvider .它加载了示例 Excel 文件包含链接图像。该代码将链接的图像替换为Aspose 徽标并使用将整个工作表渲染成单个图像图纸渲染班级。以下屏幕截图显示了示例 Excel 文件及其渲染输出图像供参考。如您所见,损坏的链接图像已替换为 Aspose 徽标。

待办事项:图片_替代_文本

示例代码

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
class ControlExternalResourcesUsingWorkbookSetting_StreamProvider
{
//Source directory
static string sourceDir = RunExamples.Get_SourceDirectory();
//Output directory
static string outputDir = RunExamples.Get_OutputDirectory();
//Implementation of IStreamProvider
class SP : IStreamProvider
{
public void CloseStream(StreamProviderOptions options)
{
}
public void InitStream(StreamProviderOptions options)
{
//string sourceDir = RunExamples.Get_SourceDirectory();
//Open the filestream of Aspose Logo and assign it to StreamProviderOptions.Stream property
FileStream fi = new FileStream(sourceDir + "sampleControlExternalResourcesUsingWorkbookSetting_StreamProvider.png", FileMode.OpenOrCreate, FileAccess.Read);
options.Stream = fi;
}
}
public static void Run()
{
//Load sample Excel file containing the external resource e.g. linked image etc.
Workbook wb = new Workbook(sourceDir + "sampleControlExternalResourcesUsingWorkbookSetting_StreamProvider.xlsx");
//Provide your implementation of IStreamProvider
wb.Settings.ResourceProvider = new SP();
//Access first worksheet
Worksheet ws = wb.Worksheets[0];
//Specify image or print options, we need one page per sheet and png output
ImageOrPrintOptions opts = new ImageOrPrintOptions();
opts.OnePagePerSheet = true;
opts.ImageType = ImageType.Png;
//Create sheet render by passing required parameters
SheetRender sr = new SheetRender(ws, opts);
//Convert your entire worksheet into png image
sr.ToImage(0, outputDir + "outputControlExternalResourcesUsingWorkbookSetting_StreamProvider.png");
Console.WriteLine("ControlExternalResourcesUsingWorkbookSetting_StreamProvider executed successfully.");
}
}