[alibaba/easyexcel]EasyExcel(2.1.0-beta4) 当head只有一列时,数据列第一列不会写入excel

2024-04-26 159 views
5

触发场景描述 当head只有一列时,数据列第一列不会写入excel

触发Bug的代码

   public GeneralExcelWriter(String filePath, List<String> heads) {
        if (StringUtil.isBlank(filePath)) {
            throw new RuntimeException("File path is blank");
        }
        if (null == heads || heads.isEmpty()) {
            throw new RuntimeException("File labels is blank");
        }

        // 临时解决 当head只有一列时,数据列第一列不会写入excel
        heads.add("错误信息");
        excelWriter = EasyExcel.write(filePath).head(initHeads(heads))
                .registerWriteHandler(getStrategy()).build();
        writeSheet = EasyExcel.writerSheet(SHEET_NAME).build();
    }

    public static List<List<String>> initHeads(List<String> heads) {
        List<List<String>> lists = new ArrayList<>(heads.size());

        heads.forEach(e -> {
            List<String> head0 = new ArrayList<>(1);
            head0.add(e);
            lists.add(head0);
        });
        return lists;
    }

提示的异常或者没有达到的效果

不正常效果:

物料编码 数据不存在

正常效果:

物料编码 abcd 数据不存在

回答

0

贴全代码。写入的代码都没看到。

0

public class GeneralExcelWriter {

public static final String SHEET_NAME = "Sheet1";

/**
 * Include file name.
 */
private ExcelWriter excelWriter;

private WriteSheet writeSheet;

public GeneralExcelWriter(String filePath, List<String> heads) {
    if (StringUtil.isBlank(filePath)) {
        throw new RuntimeException("File path is blank");
    }
    if (null == heads || heads.isEmpty()) {
        throw new RuntimeException("File labels is blank");
    }

    // 临时解决当head只有一列时,数据列第一列不会写入excel
    heads.add("错误信息");
    excelWriter = EasyExcel.write(filePath).head(initHeads(heads))
            .registerWriteHandler(getStrategy()).build();
    writeSheet = EasyExcel.writerSheet(SHEET_NAME).build();
}

public static List<List<String>> initHeads(List<String> heads) {
    List<List<String>> lists = new ArrayList<>(heads.size());

    heads.forEach(e -> {
        List<String> head0 = new ArrayList<>(1);
        head0.add(e);
        lists.add(head0);
    });
    return lists;
}

public static HorizontalCellStyleStrategy getStrategy() {
    WriteCellStyle headWriteCellStyle = new WriteCellStyle();
    headWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
    WriteFont headWriteFont = new WriteFont();
    headWriteFont.setFontHeightInPoints((short)10);
    headWriteCellStyle.setWriteFont(headWriteFont);

    return new HorizontalCellStyleStrategy(headWriteCellStyle, new WriteCellStyle());
}

public void writeRows(List<List<String>> rows) {
    excelWriter.write(rows, writeSheet);
    if (rows.get(rows.size() - 1).isEmpty()) {
        excelWriter.finish();
    }
}

}

8

还是没看到你哪里调用写入的。我建议 你参照demo,noModleWrite 然后把里面的 head和 data 都改成只有一列 试试。我测试了没问题。

0

感谢回复。我用demo跑确实也没问题。 但是项目里类似的代码确出现了这个情况,很奇怪。 现在是在excel表头加一列叫错误信息临时解决下。

导入逻辑是这样的,主线程逐行解析校验。 有错误的行把错误信息加到行尾,然后开启写excel线程写excel。 没错误的行开启写数据库线程写数据库。

以下是写excel线程代码: public class ImportWriteExcelThread implements Callable {

private static final Logger LOGGER = LoggerFactory.getLogger(ImportWriteExcelThread.class);

private BlockingQueue<List<String>> queue;

private ImportParam importParam;

private GeneralExcelWriter generalExcelWriter;

private List<List<String>> rows;

private ExcelTaskService excelTaskService;

private String filePath;

private JfsService jfsService;

ImportWriteExcelThread(ImportParam importParam) {
    queue = new LinkedBlockingQueue<>(ImpConst.BATCH_COUNT);
    this.importParam = importParam;
    initExcelWriter(importParam);
    rows = new ArrayList<>(ImpConst.BATCH_COUNT);

    excelTaskService = SpringContextUtil.getBean(ExcelTaskServiceImpl.class);
    jfsService = SpringContextUtil.getBean(JfsServiceImpl.class);
}

BlockingQueue<List<String>> getQueue() {
    return queue;
}

private void initExcelWriter(ImportParam importParam) {
    Template template = importParam.getTemplate();
    String fileName = template.getFileName() + "_"
            + DateUtil.date2Str(new Date(), DateUtil.DATE_TIME_MS) + ExcelConst.EXCEL_2007_SUFFIX;
    filePath = importParam.getWritePath() + File.separator + fileName;
    List<String> labels = template.getCols().stream().map(TemplateCol::getColLabel).collect(Collectors.toList());

    generalExcelWriter = new GeneralExcelWriter(filePath, labels);
}

@Override
public String call() throws Exception {
    LOGGER.info("=============> ImportWriteExcelThread start <=============");
    for(;;) {
        if (importParam.isException()) {
            break;
        }
        List<String> row = queue.take();
        rows.add(row);
        if (row.isEmpty()) {
            generalExcelWriter.writeRows(rows);
            overHandle();
            break;
        }
        if (ImpConst.BATCH_COUNT == rows.size()) {
            generalExcelWriter.writeRows(rows);
            rows.clear();
        }
    }
    LOGGER.info("=============> ImportWriteExcelThread end <=============");

    return "success";
}

private void overHandle() {
    File file = new File(filePath);
    String jfsPath = jfsService.upload(file, importParam.getUserId());

    ExcelTask task = new ExcelTask();
    task.setId(importParam.getTaskId());
    task.setExpFileName(file.getName());
    task.setExpFilePath(jfsPath);
    excelTaskService.modify(task);

    if (!file.delete()) {
        LOGGER.error("[{}]file delete fail");
    }
}

}