使用 WorkbookSetting.StreamProvider 控制外部资源
Contents
[
Hide
]
可能的使用场景
有时,您的 Excel 文件包含外部资源,例如链接图像等。Aspose.Cells 允许您使用以下命令控制这些外部资源工作簿.设置.StreamProvider这需要实施IStreamProvider界面。每当您尝试呈现包含外部资源(例如链接图像)的工作表时,方法IStreamProvider接口将被调用,这将使您能够对外部资源采取适当的操作。
使用 WorkbookSetting.StreamProvider 控制外部资源
下面的示例代码解释了工作簿.设置.StreamProvider.它加载了示例 Excel 文件包含链接图像。该代码将链接的图像替换为Aspose 徽标并使用将整个工作表渲染成单个图像图纸渲染班级。以下屏幕截图显示了示例 Excel 文件及其渲染输出图像供参考。如您所见,损坏的链接图像已替换为 Aspose 徽标。
示例代码
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(); | |
} |