java: excel export with HSSFWorkbook

Business: Select the file field to be exported, and then export.
The database file field value table is: information user id-file field id-file field value
already has the method of obtaining file information: getFieldValueList (List <Integer> cardFieldIds, Integer userId), incoming file field id and information user id to be exported, If the corresponding values ​​are all empty, the established default value is returned.

Effect picture:
Insert picture description here
Insert picture description here
Insert picture description here
First get the exported field cardFieldIds (strings separated by commas, such as 1,2,3) from the front end,
then get the value corresponding to the information user and the field from the database, and
finally use HSSFWorkbook to export the data.

 @ApiOperation(value = "导出信息数据字段信息", notes = "导出信息数据字段信息")
    @GetMapping("/export")
    @RequiresPermissions("archive:userCardExport:export")
    @ResponseBody
    public void export(String cardFieldIds, HttpServletResponse response) throws Exception {
        List<UserFieldVO> list = new ArrayList<>();
        List<Integer> cardFieldIdList = Convert.toListIntArray(cardFieldIds);
        List<TsysUser> archiveUsers = userCardController.listArchiveUsers().getData().getRows();

        for (TsysUser user : archiveUsers) {
            //用户-字段&值
            UserFieldVO userFieldVO = new UserFieldVO();
            userFieldVO.setUser(user);
            //字段-值集合
            Map<String, Object> map = userCardController.getFieldValueList(cardFieldIdList, user.getId());

            List<FieldValue> fieldValueList = (List<FieldValue>) map.get("fieldValueList");

            //判断字段值是否全为空(即默认值)
            boolean b = (boolean) map.get("ifAllNull");
            if (b) {
                continue;
            }

            //替换图片&附件值
            for (FieldValue fieldValue : fieldValueList) {
                if (fieldValue.getField().getFieldType().equals("附件")) {
                    fieldValue.setFieldValue("附件不支持Excel导出");
                } else if (fieldValue.getField().getFieldType().equals("图片")) {
                    fieldValue.setFieldValue("图片不支持Excel导出");
                }
                continue;
            }
            userFieldVO.setFieldValueList(fieldValueList);
            list.add(userFieldVO);
        }
		
        ExcelUtils.listToExcelByIds(list, "信息数据导出.xls", 6200, response);
    }
 public static void listToExcelByIds(List<UserFieldVO> list, String fileName, int colWidth, HttpServletResponse response) {
        try {
            response.setContentType("application/octect-stream"); // 下载文件能正常显示中文
            fileName = URLEncoder.encode(fileName, "UTF-8");
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
            OutputStream out = response.getOutputStream();

            if (list.size() == 0 || list == null) {
                Map<String, String> fields = new LinkedHashMap<>();
                fields.put("message", "导出档案信息为空!");
                ExcelUtils.ListtoExecl(null, out, fields);
                out.flush();
                out.close();
            } else {
                //  创建一个工作簿
                HSSFWorkbook workbook = new HSSFWorkbook();
                //  创建一个工作表
                HSSFSheet sheet = workbook.createSheet();
                int colSize = list.get(0).getFieldValueList().size();
                for (int j = 0; j <= colSize; j++) {
                    // 调整每一列宽度
                    sheet.autoSizeColumn((short) j);
                    // 解决自动设置列宽中文失效的问题
                    sheet.setColumnWidth(j, colWidth);
                }

                //  创建标题(第一行)
                HSSFRow title = sheet.createRow(0);
                for (int j = 0; j <= colSize; j++) {
                    HSSFCell cell = title.createCell(j);

                    //设置样式
                    HSSFCellStyle style = workbook.createCellStyle();
                    HSSFFont font = workbook.createFont();
                    font.setFontName("宋体");
                    font.setFontHeightInPoints((short) 12);// 字体大小
                    style.setFont(font); //设置字体
                    cell.setCellStyle(style);

                    //设置值
                    if (j == 0) {
                        cell.setCellValue("信息用户");
                        continue;
                    }
                    cell.setCellValue(list.get(0).getFieldValueList().get((j - 1)).getField().getFieldName());
                }

                //  创建内容(第二行开始)
                for (int i = 1; i <= list.size(); i++) {
                    HSSFRow row = sheet.createRow(i);
                    for (int j = 0; j <= colSize; j++) {
                        HSSFCell cell = row.createCell(j);
                        if (j == 0) {
                            cell.setCellValue(list.get((i - 1)).getUser().getUsername());
                            continue;
                        }
                        cell.setCellValue(list.get((i - 1)).getFieldValueList().get((j - 1)).getFieldValue());
                    }
                }
                // 将创建好的数据写入输出流
                workbook.write(out);
                // 关闭workbook
                workbook.close();
                out.flush();
                out.close();
            }
        } catch (Exception e) {
            logger.info(e.toString());
        }
    }

The above is the main logic of the background.

How to realize the front end "when checking the field, determine whether there is the same field, and if it exists, check at the same time"
first bind the click event when performing the selection operation, and then determine whether to check, if checked, the other value of the same value Multi-check boxes are checked at the same time; if they are not checked, they are not checked at the same time.

                 <div class="row">
                    <div th:each="field : ${entity['fields']}" class="col-md-3">
                      <label class="checkbox" th:value="${field.id}">
                        <input th:id="${field.id}" th:name="${entity['card'].cardName}" th:value="${field.id}"
                               th:class="styled" type="checkbox" onclick="selectCheck(this)">
                        <label th:for="${field.id}" th:text="${field.fieldName}"></label>
                      </label>
                    </div>
                  </div>
 //点击多选框事件
    function selectCheck(object) {
        let value = $(object).attr('value');
        if ($('input[value="' + value + '"]').get(0).checked) {
            $('input[value="' + value + '"]').prop("checked", true)//将其他相同值的多选框同时勾选
        } else {
            $('input[value="' + value + '"]').prop("checked", false)//同时不勾选
        }
    }

For full selection and reverse selection, you can see my blog: JQuery implements bootstrap checkbox CheckBox full selection and reverse selection

The value of the checked checkbox submitted to the background. Note that the value may be duplicated. At this time, the value needs to be repeated. See my blog: The code is simple: js removes the repeated characters in the array

After deduplication, a string of ids separated by commas is submitted to the background, such as
window.location.href = window.rootPath + “/ UserCardExportController / export? CardFieldIds =” + ids;

68 original articles have been published · 128 praised · 80,000 views

Guess you like

Origin blog.csdn.net/qq_39380155/article/details/104976811