POI操作文件(将数据填入模板文件,并下载)

Apache POI是Apache软件基金会的开放源码函式库,POI提供API给Java程序对Microsoft Office格式档案读和写的功能。

/**
	 * 下载基本信息xlsx
	 */
	@RequestMapping(value = "/printInfo",name = "下载基本信息")
	public void printInfo(HttpServletRequest request,HttpServletResponse response, KEnterPrint kEnterPrint) throws Exception {
		//1.读取excel模板
		InputStream inputStream=this.getClass().getClassLoader().getResourceAsStream("printinfo.xlsx");
		//2.创建excel对象
		XSSFWorkbook wb = new XSSFWorkbook(inputStream);
		//3.读取sheet对象
		Sheet sheet = wb.getSheetAt(0);
		//4.定义一些可复用的对象
		int rowIndex = 9; //行的索引
		int cellIndex = 1; //单元格的索引
		Row nRow = null;
		Cell nCell = null;
		//5.读取第2行
		nRow = sheet.getRow(rowIndex); // 使用后 +1
		//6.读取账户名称格
		nCell = nRow.getCell(cellIndex);
		//7.设置内容
		nCell.setCellValue(内容);

		rowIndex+=2;
		nRow = sheet.getRow(rowIndex);
		nCell = nRow.getCell(cellIndex);
		nCell.setCellValue(内容);
		//最后,下载表,字节数组的输出流,它可存可取,带缓冲区
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		wb.write(bos); //将工作簿写到输出流中
		download(bos,response,"下载文件名.xlsx");
		wb.close();
	}

	public void download(ByteArrayOutputStream byteArrayOutputStream, HttpServletResponse response, String returnName) {
		response.setContentType("application/octet-stream;charset=utf-8");
		try {
			returnName = response.encodeURL(new String(returnName.getBytes(),"iso8859-1")); //保存的文件名,必须和页面编码一致,否则乱码
			response.addHeader("Content-Disposition", "attachment;filename=" + returnName);
			response.setContentLength(byteArrayOutputStream.size());

			ServletOutputStream outputstream = response.getOutputStream(); //取得输出流
			byteArrayOutputStream.writeTo(outputstream); //写到输出流
			byteArrayOutputStream.close(); //关闭
			outputstream.flush(); //刷数据
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值