使用WorkbookSetting.StreamProvider控制外部资源

可能的使用场景

有时,您的Excel文件包含外部资源,例如链接的图片等。Aspose.Cells允许您使用Workbook.Settings.StreamProvider控制这些外部资源,该方法采用IStreamProvider接口的实现。每当您尝试渲染包含外部资源(例如链接的图片)的工作表时,将调用IStreamProvider接口的方法,从而使您能够针对外部资源采取适当的操作。

使用WorkbookSetting.StreamProvider控制外部资源

以下示例代码说明了Workbook.Settings.StreamProvider的用法。它加载包含链接图像的示例Excel文件。该代码将链接图像替换为Aspose标志,并使用SheetRender类将整个工作表渲染为单个图像。以下屏幕截图显示了示例Excel文件及其渲染输出图像以供参考。正如您所看到的那样,破损的链接图像已被替换为Aspose标志。

todo:image_alt_text

示例代码

// 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.");
}
}