将数据写入csv文件时如何转义(逗号)

时间:2016-07-04 09:41:40

标签: opencsv

我正在使用ê分隔符使用CSV Writer的write all方法从数据库中获取数据并将结果集写入csv文件。

某些列中的数据包含,(逗号),因此数据会分成多个单元格。

任何人都可以告诉如何在将数据写入csv文件时转义,(逗号)吗?

此致 拉哈西克哈

1 个答案:

答案 0 :(得分:0)

在我的情况下,我尝试使用PostgreSQL COPY命令插入并遇到此问题。我不得不将每一行解析为一个新文件。我使用NodeJS为此创建了一个小实用程序,也许它将帮助某人搜索相同的问题:

const fs = require('fs');
const path = require('path');
const readline = require('readline');

/**
 * @description formatLine should handle escaping commas w/in a representative cell.
 * @example 'row1, row2, "row3,with,embedded commas", row4
 * @param {string} str - Line to format and return. 
 * @returns {string} - 'row1, row2, "row3\,with\,embedded commas", row4
 */
const formatLine = (str) => {
    const regexp = /"(.*?)"/g;
    const array = [...str.matchAll(regexp)];
    // line growth is equal to the number of backslashes added.
    let additionsLength = 0;
    let formattedLine = '';
    if (array.length > 0) {
        array.forEach(item => {
            console.log('item: ', item);
            const index = item.index;
            const length = item[0].length;
            const pieces = item[0].split(/,/g);
            const insertMe = pieces.join('\\,');
            const beginning = (formattedLine) ? formattedLine.substring(0, index + additionsLength) : str.substring(0, index);
            const end = (formattedLine) ? formattedLine.substring(index + length + additionsLength) : str.substring(index + length);
            console.log(''.padEnd(50, '='));
            formattedLine = beginning + insertMe + end;
            additionsLength += pieces.length - 1;
        });
        return formattedLine;
    } else {
        return str;
    }
};

const writeStream = fs.createWriteStream(path.join('/postgres/', 'formatted.csv'));
const input = fs.createReadStream(path.join('/postgres/', 'input.csv'));
const rl = readline.createInterface({
    input,
    crlfDelay: Infinity
});
writeStream.on('open', () => {
    rl.on('line', (line) => {
        line = formatLine(line);
        writeStream.write(line + '\n');
    }).on('close', () => {
        writeStream.end();
    });
});