首页 > 解决方案 > 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 中分隔的数据?

标签: javascriptgoogle-apps-scriptgoogle-sheetsexport-to-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 并使用getFileByIdand setContent

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

设置内容()

编辑 2

要获取 Drive 中任何文件的 ID,您首先转到 drive 并右键单击所需的文件。单击“获取链接”,然后您将在此处找到 ID:

在此处输入图像描述

参考


推荐阅读