使用 StreamProvider 加载 HTML 到 Excel
Contents
[
Hide
]
加载包含外部资源的 HTML 时,我们经常遇到以下两个问题:
- 当加载 HTML 流时,无法通过相对路径获取 HTML 文件引用的图像和外部资源。
- 需要映射 HTML 文件中引用的外部资源路径。
本文说明了如何实现 IStreamProvider 接口,以设置 HtmlLoadOptions.StreamProvider 属性。通过实现该接口,您将能够在加载 HTML 流期间加载外部资源,或者这些外部资源是相对的。
这是展示 HtmlLoadOptions.StreamProvider 使用方法的主要代码
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
class HtmlAttachedStreamProvider implements IStreamProvider | |
{ | |
static boolean IsHRef(String picPath) | |
{ | |
//This handles http://,https:// file:// and probably ftp://. | |
if (picPath.startsWith("http://") | |
|| picPath.startsWith("https://") | |
|| picPath.startsWith("file://") | |
|| picPath.startsWith("ftp://")) | |
{ | |
return true; | |
} | |
return false; | |
} | |
static InputStream GetInputStream(String fileName) | |
{ | |
java.io.File f = new java.io.File(fileName); | |
if(!f.exists() || !f.isFile()) | |
{ | |
return null; | |
} | |
FileInputStream fis = null; | |
try | |
{ | |
return fis = new FileInputStream(f); | |
}catch(Exception e) | |
{ | |
return null; | |
} | |
} | |
public void initStream(StreamProviderOptions options) | |
{ | |
try | |
{ | |
String absolutePath = null; | |
String oldPath = options.getDefaultPath(); | |
if(oldPath.equals("/Files/Image1.png")) | |
{ | |
absolutePath = "G1.png"; | |
} | |
else if(oldPath.equals("/Files/image2.png")) | |
absolutePath = "E1.png"; | |
else if(oldPath.equals(https://www.aspose.com/templates/aspose/img/products/cells/aspose_cells-for-net.svg")) | |
absolutePath = "F1.png"; | |
if(absolutePath == null) | |
{ | |
if(IsHRef(options.getDefaultPath())) | |
{ | |
//get stream from path. | |
} | |
else | |
{ | |
options.setInputStream(GetInputStream(options.getDefaultPath())); | |
} | |
return; | |
} | |
options.setInputStream(GetInputStream(absolutePath)); | |
}catch(Exception e) | |
{ | |
} | |
} | |
public void closeStream(StreamProviderOptions options) | |
{ | |
try | |
{ | |
if(options.getStream() != null) | |
{ | |
options.getStream().close(); | |
} | |
}catch(Exception e) | |
{ | |
} | |
} | |
} | |
public static void main(String[] args)throws Exception{ | |
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET | |
HtmlAttachedStreamProvider attachedStreamProvider = new HtmlAttachedStreamProvider(); | |
HtmlLoadOptions options = new HtmlLoadOptions(); | |
options.setStreamProvider(attachedStreamProvider); | |
Workbook workbook = new Workbook( "html1.html", options); | |
workbook.save("book1.xlsx"); | |
} |