快速指南:apache poi quick-guid
在导出excle时候需要添加一些附件,可以通过超链接来实现
- 定义超链接的样式
private CellStyle createHyperlinkStyle(HSSFWorkbook hssfWorkbook){
CellStyle hLinkStyle = hssfWorkbook.createCellStyle();
Font hLinkFont = hssfWorkbook.createFont();
hLinkFont.setUnderline(Font.U_SINGLE);
hLinkFont.setColor(IndexedColors.BLUE.getIndex());
hLinkStyle.setFont(hLinkFont);
return hLinkStyle;
}
- 给单元格设置超链接
//文件保存全路径
String url = /home/attachement/test.xls
//文件名称,禁用中文,超链接导致乱码,链接不到
String fileName = "test.xls";
rowCell.setCellValue("导出单元格显示的名称");
HSSFCreationHelper creationHelper = hssfWorkbook.getCreationHelper();
//创建文件超链接
HSSFHyperlink hyperlink = creationHelper.createHyperlink(HyperlinkType.FILE);
//把附件从远程服务器下载到本地
String targetUrl = download(url, fileName);
hyperlink.setAddress(url);
rowCell.setHyperlink(hyperlink);
rowCell.setCellStyle(createHyperlinkStyle(hssfWorkbook));
private String download(String url, String fileName) {
//下载到本地电脑
String rootPath = "D:/attachment/download/";
String fullPath = rootPath + fileName;
File f = new File(url);
InputStream in = null;
OutputStream os = null;
try {
in = new FileInputStream(f);
byte[] b = new byte[512];
int len = 0;
File file = new File(fullPath);
if (!file.exists()) {
if (!file.getParentFile().exists()) {
file.mkdirs();
}
f.mkdir();
}
os = new FileOutputStream(file);
while ((len = in.read(b)) != -1) {
os.write(b, 0, len);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
if (os != null) {
try {
os.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
if (in != null) {
try {
in.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
return fullPath;
}
最后效果图:
在数据大的情况下,频繁的下载到本地肯定是行不通的,最好是有自己文件服务器,超链接下载地址,这样可以不用下载到本地电脑,速度快,效率高。
以上个人观点,不喜勿喷!