Carica HTML in Excel con StreamProvider
Quando si carica html che contiene risorse esterne, ci si imbatte spesso nei seguenti due problemi:
- Quando lo stream html viene caricato, le immagini e le risorse esterne referenziate dal file html non possono essere ottenute tramite percorsi relativi.
- I percorsi delle risorse esterne referenziati nei file html devono essere mappati.
Questo articolo spiega come implementare l’interfaccia IStreamProvider per impostare la proprietà HtmlLoadOptions.StreamProvider. Implementando questa interfaccia, sarà possibile caricare risorse esterne durante il caricamento di flussi Html o queste risorse esterne sono relative.
Questo è il codice principale che mostra l’utilizzo di 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"); | |
} |