Java導出Excel

Java導出Excel

 

太簡單了,直接上代碼吧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);
    }
View Code

 

保存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();
    }
View Code

 

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();
        }
    }
View Code
相關文章
相關標籤/搜索