javascript - Google App Script 将 CSV 导出到客户分隔符
问题描述
我有这个脚本可以将我的谷歌表格导出到 CSV 文件。我想导出一个带有客户分隔选项卡“|”的 CSV。
var pasteDataRequest = Sheets.newPasteDataRequest();
pasteDataRequest.coordinate = {
sheetId: SpreadsheetApp.getActiveSheet().getSheetId(),
rowIndex: 0,
columnIndex: 0
};
pasteDataRequest.data = data;
pasteDataRequest.type = SpreadsheetApp.CopyPasteType.PASTE_VALUES;
pasteDataRequest.delimiter = '|';
我这里有完整的脚本。
如果我以当前方式导出,它仍然由分隔的逗号“,”分割。
您如何使用“|”导出在 csv 中分隔的数据?
解决方案
如何输出类似于 CSV 但带有自定义分隔符的文本文件
这是一种非常简单的方法,可以将您的文件输出为类似 CSV 的文件类型,但不是用,
is 分隔,而是用|
您想要的任何分隔符分隔。
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
and setContent
:
DriveApp.getFileById("[FILE_ID]").setContent(csvContent)
编辑 2
要获取 Drive 中任何文件的 ID,您首先转到 drive 并右键单击所需的文件。单击“获取链接”,然后您将在此处找到 ID:
参考
推荐阅读
- python - 如何在python中打印对角矩阵?
- matlab - 我需要帮助在同一图上以不同颜色绘制 if/else 命令的不同排列
- hadoop - 资源管理器和节点管理器未启动
- python - 如何从列表中删除 unicode 中的 \xa0
- python - 如何比较多个文件,例如:比较第一个和第二个,然后使用 python 在循环内比较第二个和第三个?
- neo4j - 考虑到节点的标签已经存在,有没有办法在创建节点时自动创建关系?
- h2o - 如何对 Amazon SageMaker 训练作业控制台进行超参数化
- php - PHP 简单 HTML DOM 解析器 - 删除脚本数据
- javascript - 如何获取我的 API 请求以获取更新的数据库?
- docker - 无法备份 docker 卷