JAVA使用POI根据模版导出EXCEL

//excel模板路径  
File fi=new File(basePath+templetName);  
POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(fi));  
//读取excel模板  
HSSFWorkbook wb = new HSSFWorkbook(fs);  
//读取了模板内所有sheet内容  
HSSFSheet sheet = wb.getSheetAt(0);  
//在相应的单元格进行赋值  
HSSFCell cell = sheet.getRow(1).getCell(0);  
cell.setCellValue(XX);  


创建行设置样式,创建单元格,设置单元格样式

sheet.shiftRows(startRow, startRow+1, 1,true,false);
sheet.createRow(startRow);
sheet.getRow(startRow).setRowStyle(rowstyle);
for (int j = 0; j < 9; j++) {
      sheet.getRow(startRow).createCell(j);
}
HSSFCell temp1 = sheet.getRow(startRow).getCell(0);  
temp1.setCellValue(1);
temp1.setCellStyle(style);

输出

//修改模板内容导出新模板  
filename =filename+DateUtil.getMillisTime().toString();
FileOutputStream out = new FileOutputStream("F:/"+filename+".xls");  
wb.write(out);  
out.close();
out.flush();
下载

private void download(String path, HttpServletResponse response) {  
  try {  
       // path是指欲下载的文件的路径。  
       File file = new File(path);  
       // 取得文件名。  
       String filename = file.getName();  
       // 以流的形式下载文件。  
       InputStream fis = new BufferedInputStream(new FileInputStream(path));  
       byte[] buffer = new byte[fis.available()];  
       fis.read(buffer);  
       fis.close();  
       // 清空response  
       response.reset();  
       // 设置response的Header  
       OutputStream toClient = new BufferedOutputStream(response.getOutputStream());  
       response.setContentType("application/vnd.ms-excel;charset=gb2312");  
       response.addHeader("Content-Disposition", "attachment;filename="+ new String(filename));  
       response.addHeader("Content-Length", "" + file.length());  
       toClient.write(buffer);  
       toClient.flush();  
       toClient.close();  
     } catch (IOException ex) {  
        ex.printStackTrace();  
     }  
}




你可能感兴趣的:(poi)