JAVA使用POI根據模版匯出EXCEL
阿新 • • 發佈:2018-12-11
//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(); } }