首页 > 解决方案 > 谷歌脚本从 ftp 或谷歌驱动器导入 csv

问题描述

我正在使用脚本从链接导入 csv,但是有一种方法可以将其调整为从 ftp 链接或谷歌驱动器文件导入?谢谢这是我的剧本

function myFunction3() {
  // 1. Set the required columns as the column number.
  const requiredColumns = [1, 5, 20]; // Please set the required columns. These values are from your question.

  // 2. Retrieve CSV data from an URL.  
  const url = "https://www.stanem.it/csv/InnovaCSV.csv";
  const res = UrlFetchApp.fetch(url);

  // 3. Convert CSV data to Spreadsheet.
  const id = Drive.Files.insert({mimeType: MimeType.GOOGLE_SHEETS, title: "tempSpreadsheet"}, res.getBlob()).id;

  // 4. Delete the columns except for the required columns.
  const ss = SpreadsheetApp.openById(id);
  const sheet = ss.getSheets()[0];
  const maxColumn = sheet.getMaxColumns();
  const requests = [];  
  for (let i = 1; i <= maxColumn; i++) {
    if (!requiredColumns.includes(i)) {
      requests.push({deleteDimension: {range: {sheetId: sheet.getSheetId(), dimension: "COLUMNS", startIndex: i - 1, endIndex: i}}});
    }
  }
  Sheets.Spreadsheets.batchUpdate({requests: requests.reverse()}, id);

  // 5. Copy the values of modified CSV data to a sheet in the active Spreadsheet.
  const destinationSheetName = "Sheet1";  // Please set the destilnation sheet name in the active Spreadsheet.
  const dstss = SpreadsheetApp.getActiveSpreadsheet();
  const values = Sheets.Spreadsheets.Values.get(id, sheet.getSheetName()).values;
  Sheets.Spreadsheets.Values.update({values: values}, dstss.getId(), destinationSheetName, {valueInputOption: "USER_ENTERED"});
  
  // 6. Remove the temporat Spreadsheet.
  DriveApp.getFileById(id).setTrashed(true);
}

标签: csvgoogle-apps-scriptgoogle-sheets

解决方案


问题和解决方法:

不幸的是,在当前阶段,无法使用 UrlFetchApp 从 FTP 检索文件。那么在您的情况下,如何从 Google Drive 中检索文件?从 Google Drive 检索 CSV 文件时,修改后的脚本如下。

修改后的脚本:

请按如下方式修改您的脚本。在这个修改后的脚本中,它假设 CSV 文件放在您的 Google Drive 中。

从:
// 2. Retrieve CSV data from an URL.  
const url = "https://www.stanem.it/csv/InnovaCSV.csv";
const res = UrlFetchApp.fetch(url);

// 3. Convert CSV data to Spreadsheet.
const id = Drive.Files.insert({mimeType: MimeType.GOOGLE_SHEETS, title: "tempSpreadsheet"}, res.getBlob()).id;
至:
// 3. Convert CSV data to Spreadsheet.
const fileId = "### fileId of CSV file on Google Drive ###";  // Please set the file ID of CSV file.
const id = Drive.Files.copy({mimeType: MimeType.GOOGLE_SHEETS, title: "tempSpreadsheet"}, fileId).id;
  • 在这种情况下,CSV 文件可以用Drive.Files.copy.

参考:


推荐阅读