太簡單了,直接上代碼吧app
生成Excelide
@RequestMapping("/importExcel") @ResponseBody public void importExcel() throws Exception { File file = File.createTempFile("Excel模板", ".xls"); WritableWorkbook workbook = Workbook.createWorkbook(file); WritableSheet sheet = workbook.createSheet("Excel模板", 0); WritableFont font = new WritableFont(WritableFont.ARIAL, 12); // 字的大小 WritableCellFormat format = new WritableCellFormat(font); format.setAlignment(Alignment.CENTRE); // 水平居中 format.setVerticalAlignment(VerticalAlignment.CENTRE); // 垂直居中 sheet.addCell(new Label(0, 0, "姓名", format)); sheet.addCell(new Label(1, 0, "手機號", format)); sheet.addCell(new Label(0, 1, "a", format)); sheet.addCell(new Label(1, 1, "b", format)); sheet.setColumnView(0, 13); // 設置列寬 sheet.setColumnView(1, 14); go(workbook, file); }
保存Excel工具
private void go(WritableWorkbook workbook, File file) throws Exception { workbook.write(); workbook.close(); response.setContentType("application/x-xls"); response.addHeader("Content-Disposition", "attachment; filename=\"" + URLEncoder.encode(file.getName(), "utf-8") + "\""); response.setContentLength((int) file.length()); // 文件大小 FileUtil.i2o(new BufferedInputStream(new FileInputStream(file)), response.getOutputStream()); // 最後刪除臨時文件 file.deleteOnExit(); }
FileUtil 工具類 i2o 方法spa
/** * 輸入流寫到輸出流 */ public static void i2o(InputStream is, OutputStream os) { try { byte[] b = new byte[1024 * 1024]; // 一次讀取1M int n; while ((n = is.read(b)) != -1) os.write(b, 0, n); is.close(); os.flush(); os.close(); } catch (IOException e) { e.printStackTrace(); } }