码迷,mamicode.com
首页 > 编程语言 > 详细

Java导出Excel

时间:2017-11-17 13:33:23      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:手机   div   format   ble   工具   filename   work   position   let   

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

 

Java导出Excel

标签:手机   div   format   ble   工具   filename   work   position   let   

原文地址:http://www.cnblogs.com/liaolongjun/p/7850884.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!