Cargar Html a Excel con StreamProvider
Cuando se carga HTML que contiene recursos externos, a menudo nos enfrentamos a los siguientes dos problemas:
- Cuando se carga el flujo de html, las imágenes y recursos externos referenciados por el archivo html no se pueden obtener a través de rutas relativas.
- Las rutas de recursos externos referenciadas en archivos HTML deben ser mapeadas.
Este artículo explica cómo implementar la interfaz IStreamProvider para establecer la propiedad HtmlLoadOptions.StreamProvider. Al implementar esta interfaz, podrá cargar recursos externos durante la carga de flujos de HTML o estos recursos externos son relativos.
Este es el código principal que muestra el uso de 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"); | |
} |