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();
}
}