Javascript CSV 导出逗号问题

标签 javascript

我有一个 javascript 函数,用于将一些 JSON 数据转换为 excel 导出。在大多数情况下,一切都运行良好。

但是我注意到我的一个列名现在有一个逗号(有意)LastName, FirstName

使用我现有的代码,当我希望它是一个列标题时,它会导致标题列被分离并移到它自己的列中。

/**
 * Convert the JSON to a CSV File
 * @param {*} JSONData 
 * @param {*} ReportTitle 
 * @param {*} ShowLabel 
 */
function JSONToCSVConvertor(JSONData, ReportTitle, ShowLabel) {

    //If JSONData is not an object then JSON.parse will parse the JSON string in an Object
    var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;
    var CSV = '';
    //This condition will generate the Label/Header
    if (ShowLabel) {
        var row = "";

        //This loop will extract the label from 1st index of on array
        for (var index in arrData[0]) {
            //Now convert each value to string and comma-seprated
            row += index + ',';
        }
        row = row.slice(0, -1);
        //append Label row with line break
        CSV += row + '\r\n';
    }

    //1st loop is to extract each row
    for (var i = 0; i < arrData.length; i++) {
        var row = "";
        //2nd loop will extract each column and convert it in string comma-seprated
        for (var index in arrData[i]) {
            row += '"' + arrData[i][index] + '",';
        }
        row.slice(0, row.length - 1);
        //add a line break after each row
        CSV += row + '\r\n';
    }

    if (CSV == '') {
        alert("Invalid data");
        return;
    }

    var csv = CSV;
    blob = new Blob([csv], {
        type: 'text/csv'
    });


    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        window.navigator.msSaveOrOpenBlob(blob, ReportTitle);
    } else {
        var objectUrl = URL.createObjectURL(blob);
        window.open(objectUrl);
    }


}

我认为我的错误在 if (ShowLabel) { 语句中。

有没有一种方法可以忽略标题行中的逗号,以便我的列保持对齐?

错误:

enter image description here

期望:

enter image description here

关于如何忽略标题行中的逗号有什么想法吗?

最佳答案

我认为您应该在标签周围添加引号,这样内部的逗号(引号)就不会被视为分隔符

for (var index in arrData[0]) {
    //Now convert each value to string and comma-seprated
    row += '\"' + index + '\",';
}

在您的屏幕截图中,Bob, Jones 已正确分配给一个单元格,尽管有一个逗号。例如,如果您在记事本中打开 CSV 文件,您应该会看到 Bob, Jones 有引号。

关于Javascript CSV 导出逗号问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53596611/

相关文章:

javascript - Base64上传图片问题

javascript - 检查 execCommand createlink 状态

javascript - 如何使用 JavaScript 验证此 HTML 表单?

javascript - 在 Vue JS 3 的 CSS 类中使用模板变量

javascript - 更改输入图标并删除以前的图标(Jquery)

javascript - 通过 javascript 访问 DOM - Javascript

JavaScript 比较

javascript - 如何在 ionic 4 中移动搜索栏右侧搜索栏的搜索图标

javascript - ReadyState 没有更改为 4

javascript - 使用 jQuery 隐藏页面 Load() 上的元素