Java导出Excel

Java导出Excel

太简单了,直接上代码吧

生成Excel

    @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 方法

    /**
     * 输入流写到输出流
     */
    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
原文地址:https://www.cnblogs.com/liaolongjun/p/7850884.html