使用Google Apps脚本创建CSV文件时,如何添加逗号? [英] How can I include commas when creating CSV files with Google apps script?
问题描述
我正在开发一些代码,以使用Google Apps脚本创建CSV文件.我知道如何创建CSV文件,但是当字符串值包含逗号时会出现问题.如果数组元素带有逗号,则在创建CSV文件时这些元素将被分隔.
I'm working on developing some codes to create CSV files with Google apps script. I know how to create CSV files, but I have a problem when string values have commas. If array elements have commas, those elements will be separated when CSV files are created.
我正在处理此代码,因为我想将CSV文件上传到EC网站,例如eBay,亚马逊等.因此,格式由它们固定.我无法避免在数组元素中使用逗号.
I am working on this code because I would like to upload CSV files to EC websites, such as eBay, amazon and things like that. So the format is fixed by them. There is no way I can avoid using commas in the array elements.
我试图将"括在逗号中(例如:,"),但它根本没有用.我也尝试使用其他定界符,但也没有用.
I tried to put "" to brace commas (ex: ","), but it didn't work at all. I also attempted to use different delimiter, but it didn't work either.
我的代码如下:
var folderId = DriveFolderId
var array = [
["title1", "title2", "title3"],
["value1", "value2-1,value2-2", "value3"],
]
for (var i in array) {
array[i] = array[i].join(",");
}
var array = array.join("\n");
var folder = DriveApp.getFolderById(folderId);
var now = Utilities.formatDate(new Date(), "JST", "yyyy_MM_dd_HH_mm_ss");
folder.createFile(now + ".csv", array, "text/csv");
上面的代码工作得很好,除非数组元素中没有逗号.如果有逗号,则在创建CSV文件时将它们分开.在上面的示例中,它创建了一个像这样的文件:
Codes above works just fine unless array elements don't have commas in it. If they have commas, they are separated when creating CSV files. In the above example, it creates a file like this:
[title1],[title2],[title3]
[title1],[title2],[title3]
[值1],[值2-1],[值2-2],[值3]
[value1],[value2-1],[value2-2],[value3]
我希望它像这样:
[title1],[title2],[title3]
[title1],[title2],[title3]
[值1],[值2-1,值2-2],[值3]
[value1],[value2-1,value2-2],[value3]
当执行 folder.createFile(now +".csv",array,"text/csv")
时,它会破坏我的所有精力.
When it executes folder.createFile(now + ".csv", array, "text/csv")
, it ruins all my efforts.
有人知道如何解决这个问题吗?
Does anyone know how to solve this issue?
推荐答案
- 您要使用问题中的脚本创建如下所示的CSV文件.
如果我的理解是正确的,那么该修改如何?
If my understanding is correct, how about this modification?
var array = [
["title1", "title2", "title3"],
["value1", "value2-1,value2-2", "value3"],
]
for (var i in array) {
array[i] = array[i].join(",");
}
至:
var array = [
["title1", "title2", "title3"],
["value1", "value2-1,value2-2", "value3"],
];
array = array.map(function(e) {return e.map(function(f) {return ~f.indexOf(",") ? '"' + f + '"' : f})}); // Added
for (var i in array) {
array[i] = array[i].join(",");
}
- 在此修改中,当值具有
,
,"value2-1,value2-2"
转换为"\" value2-1,value2-2 \"
.这样,可以检索如上图所示的结果. - In this modification, when the value has
,
,"value2-1,value2-2"
is converted to"\"value2-1,value2-2\""
. By this, the result like above image can be retrieved.
如果这不是您想要的结果,我表示歉意.
If this was not the result you want, I apologize.
这篇关于使用Google Apps脚本创建CSV文件时,如何添加逗号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!