【问题标题】:Google App Script export CSV to a customer DelimiterGoogle App Script 将 CSV 导出到客户分隔符
【发布时间】:2021-08-08 12:52:52
【问题描述】:

我有这个脚本可以将我的谷歌表格导出到 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 = '|';

我有完整的脚本here

如果我以当前方式导出,它仍然用分隔的逗号“,”分割。

我如何用“|”导出我在 csv 中分隔的数据?

【问题讨论】:

标签: javascript google-apps-script google-sheets export-to-csv


【解决方案1】:

如何输出类似于 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 并使用 getFileByIdsetContent

DriveApp.getFileById("[FILE_ID]").setContent(csvContent)

setContent()

编辑 2

要获取云端硬盘中任何文件的 ID,请先转到云端硬盘并右键单击所需的文件。点击“获取链接”,然后在这里你会找到ID:

参考文献

【讨论】:

  • 你真是个救世主,非常感谢!我会试试这个,看看效果如何!我很难找到解决方案。问题:如果我每小时运行一次触发器,它会覆盖当前文件还是每次都创建一个副本?在我的最终解决方案中,我需要覆盖以简单地覆盖同一个文件......所以它不会更改名称。感谢您提供详细的示例!
  • 很高兴。因为它每次都会创建一个新文件。我添加了一个编辑来展示您如何每次都替换同一个文件。
  • 通常在 Google 表格上,我会在最后得到文件 ID... 示例 edit#gid=1769972812。现在在谷歌文档上,我只得到这个链接docs.google.com/document/d/…,所以很明显,当我把 DriveApp.getFileById("[0eI7WAO688nQHRqj7ymscN5I5fJpP4fVTUn_qZMuq3Y]").setContent(csvContent) 它不起作用....我找不到这个文档的文件 ID。 .. 怎么会?
  • 谷歌文档与 csv 文件有很大不同。如果您想将类似 csv 的内容输出到 Google Doc 中,则过程非常不同。此答案向您展示了如何将其放入 CSV/PLAIN_TEXT 文件中,我再次编辑了答案,其中包含如何获取驱动器中任何文件的 ID。
猜你喜欢
  • 2016-01-26
  • 1970-01-01
  • 1970-01-01
  • 2014-08-14
  • 1970-01-01
  • 1970-01-01
  • 2016-03-13
  • 2018-08-21
  • 1970-01-01
相关资源
最近更新 更多