تحميل HTML إلى Excel باستخدام StreamProvider
عند تحميل HTML الذي يحتوي على موارد خارجية، نواجه غالبًا المشكلتين التاليتين:
- عندما يتم تحميل تدفق HTML، لا يمكن الحصول على الصور والموارد الخارجية المشار إليها في ملف HTML من خلال المسارات النسبية.
- يجب تعيين مسارات الموارد الخارجية المشار إليها في ملفات HTML.
يشرح هذا المقال كيفية تنفيذ واجهة IStreamProvider لضبط خاصية HtmlLoadOptions.StreamProvider. من خلال تنفيذ هذه الواجهة، ستكون قادرًا على تحميل الموارد الخارجية أثناء تحميل تيارات HTML أو أن تكون هذه الموارد الخارجية نسبية.
هذا هو الكود الرئيسي الذي يظهر استخدام HtmlLoadOptions.StreamProvider
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"); | |
} |