JAVA的poi实现模版导出excel
发布时间:2011-09-23 15:34:35
发布时间:2011-09-23 15:34:35
String accident_id = request.getParameter("accident_id");
String OnputimagePath = null;
/**************使用poi实现excel模版 导出excel********************/
try {
POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream("d:\\设备异常分析报告.xls"));
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFSheet sheet = wb.getSheet("设备异常分析报告");
HSSFRow row = sheet.getRow(2);
HSSFCell cell = row.getCell((short) 2);
if (cell == null)
cell = row.createCell((short) 2);
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
cell.setCellValue("12321212");
ByteOutputStream byteOut = new ByteOutputStream();
String InputimagePath = "d:\\1012051443548604211337adf6.jpg";
BufferedImage bufferImg = ImageIO.read(new File(InputimagePath));
ImageIO.write(bufferImg,"JPG",byteOut);
//设置图片大小,位置
HSSFClientAnchor anchor = new HSSFClientAnchor(5,0,500,122,(short) 0, 5,(short)10,15);
//创建
HSSFPatriarch patri = sheet.createDrawingPatriarch();
patri.createPicture(anchor ,wb.addPicture(byteOut.toByte(), HSSFWorkbook.PICTURE_TYPE_PNG));
// 输出文件
OnputimagePath = "d:\\test1.xls";
FileOutputStream fileOut = new FileOutputStream(OnputimagePath);
wb.write(fileOut);
fileOut.close();
} catch (Exception e) {
e.printStackTrace();
}
// 检查文件是否存在
File obj = new File(OnputimagePath);
if (!obj.exists()) {
response.setContentType("text/html;charset=GBK");
response.getWriter().print("指定文件不存在!");
return;
}
// 读取文件名:用于设置客户端保存时指定默认文件名
int index = OnputimagePath.lastIndexOf("\\"); // 前提:传入的path字符串以“\”表示目录分隔符
String fileName = OnputimagePath.substring(index + 1);
// 写流文件到前端浏览器
ServletOutputStream out = response.getOutputStream();
response.setHeader("Content-disposition", "attachment;filename=" + fileName);
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(new FileInputStream(OnputimagePath));
bos = new BufferedOutputStream(out);
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
} catch (IOException e) {
throw e;
} finally {
if (bis != null)
bis.close();
if (bos != null)
bos.close();
}