在Google工作表中以(.csv)格式导出多个工作表

tv6aics1  于 2022-12-06  发布在  Go
关注(0)|答案(1)|浏览(170)

在上面的图片中,你可以看到我在一个谷歌工作表中创建了很多文件。现在我想要的是在单独的文件中导出所有这些工作表文件。如果我点击exprt按钮,它会将文件保存为主文件,但我想使每个spreeadsheet一个单独的csv文件。
例如:加州州.csv阿拉斯加州.csv
任何帮助都是感激不尽的。
谢谢
我尝试默认的导出方法,但这不是我想要的。
期望得到我所有的spreeadsheet在单独的.csv文件

rxztt3cl

rxztt3cl1#

您可以使用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')
  );
}

相关问题