热衷于在 Google 表格中以 (.csv) 格式导出多张工作表

问题描述 投票:0回答:1

在上图中,您可以看到我在一张谷歌工作表中创建了很多文件。现在我想要的是将所有这些工作表文件导出为“.csv”格式的单独文件。如果我单击 exprt 按钮,它会将文件另存为主文件,但我想将每个电子表格制作为单独的 csv 文件。

例如: 加利福尼亚州.csv 阿拉斯加.csv

如有任何帮助,我们将不胜感激。

谢谢

我尝试了默认的导出方法,但这不是我想要的。

希望将我的所有电子表格放在单独的 .csv 文件中

csv google-sheets export-to-csv
1个回答
1
投票

您可以使用 Apps Script 来做到这一点,如下所示:

'use strict';

function test() {
  const ss = SpreadsheetApp.getActive();
  const timezone = ss.getSpreadsheetTimeZone();
  const prefix = Utilities.formatDate(new Date(), timezone, 'yyyy-MM-dd ');
  console.log(`Exporting files...`);
  const result = exportTabsAsCsvToDrive_(ss, /./i, prefix);
  console.log(`Wrote ${result.files.length} files in folder '${result.folder.getName()}' at ${result.folder.getUrl()}.`);
}

/**
* Exports sheets each into its own CSV file.
*
* @param {SpreadsheetApp.Spreadsheet} ss Optional. A spreadsheet with sheets to export. Defaults to the active spreadsheet.
* @param {RegExp} sheetNameRegex Optional. A regex to match to sheet names. Defaults to all sheets.
* @param {String} prefix Optional. A text string to prepend to filenames. Defaults to ''.
* @param {String} suffix Optional. A text string to append to filenames. Defaults to ''.
* @param {DriveApp.Folder} folder Optional. The folder where to save the files in. Defaults to the spreadsheet's folder.
* @return {Object} { folder, files[] }
*/
function exportTabsAsCsvToDrive_(ss = SpreadsheetApp.getActive(), sheetNameRegex = /./i, prefix = '', suffix = '', folder) {
  // version 1.1, written by --Hyde, 2 December 2022
  //  - see https://stackoverflow.com/a/74654152/13045193
  folder = folder || DriveApp.getFileById(ss.getId()).getParents().next();
  const files = [];
  ss.getSheets().forEach(sheet => {
    const sheetName = sheet.getName();
    if (!sheetName.match(sheetNameRegex)) return;
    const filename = prefix + sheetName + suffix + '.csv';
    const values = sheet.getDataRange().getDisplayValues();
    const csvData = textArrayToCsv_(values);
    files.push(DriveApp.createFile(filename, csvData, MimeType.CSV).moveTo(folder));
  });
  return { folder: folder, files: files };
}

/**
* Converts text to a CSV format.
* When the data looks like this:

  header A1       header B1                   header C1
  text A2         text with comma, in B2      text with "quotes" in C2

* ...the function will return this:

  "header A1", "header B1", "header C1"
  "text A2", "text with comma, in B2", "text with \"quotes\" in C2"

* Lines end in a newline character (ASCII 10).
*
* @param {String[][]} data The text to convert to CSV.
* @return {String} The text converted to CSV.
*/
function textArrayToCsv_(data) {
  // version 1.0, written by --Hyde, 20 June 2022
  //  - see https://stackoverflow.com/a/72689533/13045193
  return (
    data.map(row => row.map(value => `"${value.replace(/"/g, '\\"')}"`))
      .map(row => row.join(', '))
      .join('\n')
  );
}
© www.soinside.com 2019 - 2024. All rights reserved.