【java】导出excel

【前言】

        我们项目经理要看一下贝瓦给我们提供了哪些数据,所以就导出一下咯

【正文】

        废不多话,直接上代码

  /**
     * 从贝瓦获取指定频道下的作品并导出到excel文件中
     *
     * @param albumExportPreUrl 获取数据url的前部分
     * @param page              当前页
     */
    public void exportAlbumOrContent(String fileNames, String albumExportPreUrl,
                                       String page) throws Exception {

        //文件相关,UUID 防重名,以为对方一次只能给20条数据(真分页)
        UUID uuid = UUID.randomUUID();
        String fileName = fileNames + uuid.toString() + "专辑.xls";
        File file = new File(fileName);

        String contentOfCatUrl = albumExportPreUrl + page + "&access-token=" + bevaResource.getBevaToken();
        ;
        JSONObject formResource = getJSONObjectBeva(contentOfCatUrl);
        //获取表格的列名,没有tags,因为是空的
        Map<String, String> bevaDataExcelTitle = BevaDataMapOfExcelTitle();//设置标题
        JSONArray jsonArray = formResource.getJSONObject("data").getJSONArray("items");
        //生成excel文件
        saveFile(bevaDataExcelTitle, jsonArray, file);

    }
   /**
     * 为url添加token,并且调用贝瓦的数据
     *
     * @param strUrl 基础url
     * @return 贝瓦的数据
     */
    private JSONObject getJSONObjectBeva(String strUrl) throws Exception {

        strUrl = strUrl + "&access-token=" + bevaResource.getBevaToken();
        strUrl = strUrl.replaceAll("[;\"]", "");//拼接的url 去除分隔符符合url要求
        return restTemplate.getForEntity(strUrl, JSONObject.class).getBody();
    }

设置标题:

 /**
     * 导出excel的列名
     *
     * @return
     */
    private Map<String, String> BevaDataMapOfExcelTitle() {
        Map<String, String> excelTitle = new LinkedHashMap<>();
        excelTitle.put("id", "作品id");
        excelTitle.put("name", "作品名称");
        excelTitle.put("cont_type", "作品类型");
        excelTitle.put("ad_play_type", "支持广告播放的情况");
        excelTitle.put("description", "作品描述");
        excelTitle.put("play_count", "作品的总播放次数");
        excelTitle.put("vip_label", "是否需要vip和收费");
        excelTitle.put("img_small", "小的图片");
        excelTitle.put("img_middle", "中等的图片");
        excelTitle.put("img_big", "大的图片");
        excelTitle.put("published_at", "专辑发布时间");
        excelTitle.put("created_at", "专辑最后修改时间");
        excelTitle.put("updated_at", "专辑最后修改时间");
        return excelTitle;
    }

导出:

saveFile(bevaDataExcelTitle, jsonArray, file);
   /**
     * 导出文件
     *
     * @param headData
     * @param listData
     * @param file
     * @return
     */
    private File saveFile(Map<String, String> headData, JSONArray listData, File file) {
        // 创建工作薄
        HSSFWorkbook hssfWorkbook = new HSSFWorkbook();
        // sheet:一张表的简称
        // row:表里的行
        // 创建工作薄中的工作表
        HSSFSheet hssfSheet = hssfWorkbook.createSheet();
        // 创建行
        HSSFRow row = hssfSheet.createRow(0);
        // 创建单元格,设置表头 创建列
        HSSFCell cell = null;
        // 初始化索引
        int rowIndex = 0;
        int cellIndex = 0;

        // 创建标题行
        row = hssfSheet.createRow(rowIndex);
        rowIndex++;
        // 遍历标题
        for (String h : headData.keySet()) {
            // 创建列
            cell = row.createCell(cellIndex);
            // 索引递增
            cellIndex++;
            // 逐列插入标题
            cell.setCellValue(headData.get(h));
        }

        // 得到所有记录 行:列
        JSONObject record = null;

        if (listData != null) {
            // 获取所有的记录 有多少条记录就创建多少行
            for (int i = 0; i < listData.size(); i++) {
                row = hssfSheet.createRow(rowIndex);
                // 得到所有的行 一个record就代表 一行
                record = listData.getJSONObject(i);
                // 下一行索引
                rowIndex++;
                // 刷新新行索引
                cellIndex = 0;
                // 在有所有的记录基础之上,便利传入进来的表头,再创建N行
                for (String h : headData.keySet()) {
                    cell = row.createCell(cellIndex);
                    cellIndex++;
                    // 按照每条记录匹配数据
                    cell.setCellValue(record.get(h) == null ? "" : record.get(h).toString());
                }
            }
        }
        try {
            FileOutputStream fileOutputStreane = new FileOutputStream(file);
            hssfWorkbook.write(fileOutputStreane);
            fileOutputStreane.flush();
            fileOutputStreane.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }

会导出到文件file中的路径下,导出很多文件手动合并显然不太科学、网上看了一下excel本身提供了函数支持,java有代码,下面的代码我没有试验、看着挺不错、充一下门面:

/**
     * TODO合并excel为一个文件
     * @param outputFileName
     * @param inputFileNameArray
     */
    //@RequestMapping(value = "/mergExcel", method = RequestMethod.GET)
    public void mergeExcel(@RequestParam(value = "outputFileName") String outputFileName,
                           @RequestBody String... inputFileNameArray) {

        if (inputFileNameArray.length == 1) {
            return;
        }

        try {
            WritableWorkbook outputExcel = Workbook.createWorkbook(new File(outputFileName));
            int index = 0;
            for (String fileName : inputFileNameArray) {
                // 创建excel文件的工作簿对象book
                Workbook inputExcel = Workbook.getWorkbook(new FileInputStream(fileName));
                // 获取excel文件工作簿的工作表数量sheets
                Sheet[] sheets = inputExcel.getSheets();
                for (Sheet sheet : sheets) {
                    WritableSheet writableSheet = outputExcel.createSheet(sheet.getName(), index);
                    copy(sheet, writableSheet);
                    index++;
                }
            }
            /** **********将以上缓存中的内容写到EXCEL文件中******** */
            outputExcel.write();
            outputExcel.close();
        } catch (Exception e) {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            e.printStackTrace(pw);
        }
    }

    private static void copy(Sheet formSheet, WritableSheet toWritableSheet) {
        // 行数
        int rows = formSheet.getRows();
        // 列数
        int columns = formSheet.getColumns();
        for (int rowIndex = 0; rowIndex < rows; rowIndex++) {
            for (int columnIndex = 0; columnIndex < columns; columnIndex++) {
                // 获取当前工作表.row_index,column_index单元格的cell对象
                Cell cell = formSheet.getCell(columnIndex, rowIndex);
                try {
                    CellFormat wcf = new WritableCellFormat();
                    if (cell.getCellFormat() != null) {
                        wcf = cell.getCellFormat();
                    }
                    toWritableSheet.addCell(new Label(columnIndex, rowIndex, cell.getContents(), wcf));
                } catch (Exception e) {
                    StringWriter sw = new StringWriter();
                    PrintWriter pw = new PrintWriter(sw);
                    e.printStackTrace(pw);
                }
            }
        }
    }

【后语】

        有一个动态获取token的过程,暂时不写了,下篇说或者看心情再说吧

猜你喜欢

转载自blog.csdn.net/ma15732625261/article/details/80492030