使用Univocity在输出CSV中设置自定义标题

时间:2017-05-18 11:21:40

标签: java univocity

我使用Univocity将Resultset转换为CSV格式的字符串,使用以下代码:

StringWriter stringWriter = new StringWriter();

    CsvWriterSettings csvWriterSettings = new CsvWriterSettings();

    ResultSetMetaData metaData = resultSet.getMetaData();

    int columnCount = metaData.getColumnCount();

    String headers[] = new String[columnCount];

    for (int i = 0; i < columnCount; i++) {

        headers[i] = metaData.getColumnLabel(i + 1);

    }

    for (int i = 0; i < headers.length; i++) {

        if (fieldMapping != null && fieldMapping.containsKey(headers[i])) {

            headers[i] = fieldMapping.get(headers[i]);

        }
    }

    csvWriterSettings.setHeaders(headers);

    csvWriterSettings.setHeaderWritingEnabled(true);

    if (csvSeparator != null) {

        csvWriterSettings.getFormat().setDelimiter(csvSeparator.charAt(0));

    }

    if (isQuoteFields) {

        csvWriterSettings.setQuoteAllFields(true);
    }

    if (isCStyleEscape) {

        csvWriterSettings.getFormat().setQuoteEscape(',');

        csvWriterSettings.getFormat().setCharToEscapeQuoteEscaping('\\');

    }

    CsvRoutines csvRoutines = new CsvRoutines(csvWriterSettings);

    csvRoutines.write(resultSet, stringWriter);

    return stringWriter.toString();

我尝试在输出中设置自定义标头,但返回的输出始终具有默认标头。

有没有办法在输出csv格式字符串中设置自己的标题值。

1 个答案:

答案 0 :(得分:0)

这是一个错误,我刚刚打开了一个错误报告here),因此这将在2.5.0+版本中开箱即用。目前有一个解决方法:

首先设置您想要的标题:

String headers[] = {"My", "Custom", "Header"};
csvWriterSettings.setHeaders(headers);

将带有标题的单行写入输出:

CsvWriter headerWriter = new CsvWriter(stringWriter, csvWriterSettings);
headerWriter.writeRow(headers);

转储ResultSet

CsvRoutines csvRoutines = new CsvRoutines(csvWriterSettings);
csvRoutines.write(resultSet, stringWriter);

关闭您创建的编辑器以生成标题:

headerWriter.close();

希望这有帮助。