zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    时间处理得到UTC时间
    java数据同步陷阱
    360公司2016笔试题
    YTU 1439: 2.4.5 Fractions to Decimals 分数化小数
    YTU 2422: C语言习题 n个数逆序
    YTU 2421: C语言习题 矩形法求定积分
    YTU 2427: C语言习题 整数排序
    YTU 2832: 使用指针访问数组元素--程序填空
    YTU 1050: 写一个函数,使给定的一个二维数组(3×3)转置,即行列互换
    HDU 1069:Monkey and Banana
  • 原文地址:https://www.cnblogs.com/liaolongjun/p/7850884.html
Copyright © 2011-2022 走看看