使用WorkbookSetting.StreamProvider控制外部资源
可能的使用场景
有时,您的Excel文件包含外部资源,例如链接的图像等。Aspose.Cells允许您使用Workbook.Settings.StreamProvider控制这些外部资源,该方法接受IStreamProvider接口的实现。每当您尝试呈现包含外部资源的工作表时,将调用IStreamProvider接口的方法,这将使您能够针对外部资源采取适当的操作。
使用WorkbookSetting.StreamProvider控制外部资源
以下示例代码解释了如何使用Workbook.Settings.StreamProvider。它加载包含链接图像的样本Excel文件。代码将链接图像替换为Aspose Logo,并使用SheetRender类将整个工作表呈现为单个图像。以下屏幕截图显示了示例Excel文件及其渲染输出图像供参考。正如您所见,损坏的链接图像已替换为Aspose Logo。
示例代码
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java | |
//Implementation of IStreamProvider | |
class SP implements IStreamProvider | |
{ | |
public void closeStream(StreamProviderOptions arg0) throws Exception { | |
} | |
public void initStream(StreamProviderOptions options) throws Exception { | |
//Open the filestream of Aspose Logo and assign it to StreamProviderOptions.Stream property | |
File imgFile = new File(srcDir + "sampleControlExternalResourcesUsingWorkbookSetting_StreamProvider.png"); | |
byte[] bts = new byte[(int) imgFile.length()]; | |
FileInputStream fin = new FileInputStream(imgFile); | |
fin.read(bts); | |
fin.close(); | |
ByteArrayOutputStream baout = new ByteArrayOutputStream(); | |
baout.write(bts); | |
baout.close(); | |
options.setStream(baout); | |
} | |
} | |
public void Run() throws Exception { | |
System.out.println("Aspose.Cells for Java Version: " + CellsHelper.getVersion()); | |
//String srcDir = Utils.Get_SourceDirectory(); | |
//String outDir = Utils.Get_OutputDirectory(); | |
//Load sample Excel file containing the external resource e.g. linked image etc. | |
Workbook wb = new Workbook(srcDir + "sampleControlExternalResourcesUsingWorkbookSetting_StreamProvider.xlsx"); | |
//Provide your implementation of IStreamProvider | |
wb.getSettings().setStreamProvider(new SP()); | |
//Access first worksheet | |
Worksheet ws = wb.getWorksheets().get(0); | |
//Specify image or print options, we need one page per sheet and png output | |
ImageOrPrintOptions opts = new ImageOrPrintOptions(); | |
opts.setOnePagePerSheet(true); | |
opts.setImageType(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, outDir + "outputControlExternalResourcesUsingWorkbookSettingStreamProvider.png"); | |
// Print the message | |
System.out.println("ControlExternalResourcesUsingWorkbookSetting_StreamProvider executed successfully."); | |
} | |
public static void main(String[] args) throws Exception { | |
new ControlExternalResourcesUsingWorkbookSetting_StreamProvider().Run(); | |
} |