如何输出类似于 CSV 但带有自定义分隔符的文本文件
这是一种非常简单的方法,可以将您的文件作为类似 CSV 的文件类型输出,但不是用, 分隔,而是用| 或您想要的任何分隔符分隔。
function createCsvContent(values, delimiter) {
// This converts the values 2D array into a simple array of strings delimited by the delimiter
const stringArray = values.map(row => row.join(delimiter))
// Then it joins all the strings with newlines
const output = stringArray.join("\n")
return output
}
function createCsv() {
// Get all the values from the sheet as a 2D array
const file = SpreadsheetApp.getActive();
const sheet = file.getSheetByName("Sheet1");
const range = sheet.getDataRange();
const values = range.getValues();
// call the function to create the csv-like content
const csvContent = createCsvContent(values, "|")
// create the file in drive
DriveApp.createFile('csvFile', csvContent, MimeType.PLAIN_TEXT)
}
请注意,最后一行将文件创建为纯文本文件。我打算制作这个 CSV,但由于它不再以逗号分隔,因此不能再将其归类为 CSV 文件。虽然如果你改变它,它会照常工作。
主要的创建发生在createCsvContent 函数中。它使用数组的map 方法将从电子表格中获取的二维数组转换为简单的字符串数组。
发件人:
[
[1,2,3],
[4,5,6],
[7,8,9],
]
收件人:
[
"1|2|3",
"4|5|6",
"7|8|9",
]
然后最后在主数组上使用另一个join 将其转换为:
"1|2|3\n4|5|6\n7|8|9"
\n 的意思是“换行符”,最后它会变成这样:
1|2|3
4|5|6
7|8|9
然后是调用DriveApp.createFile 并使用您想要的文件名、createCsvContent 函数生成的内容和 mime 类型。
编辑
每次都替换同一个文件,而不是:
// create the file in drive
DriveApp.createFile('csvFile', csvContent, MimeType.PLAIN_TEXT)
您需要获取“csv”的文件 ID 并使用 getFileById 和 setContent:
DriveApp.getFileById("[FILE_ID]").setContent(csvContent)
setContent()
编辑 2
要获取云端硬盘中任何文件的 ID,请先转到云端硬盘并右键单击所需的文件。点击“获取链接”,然后在这里你会找到ID:
参考文献