google 脚本仅导入带有脚本的几列

google script import only few column with script

有一个包含很多列和原始数据的 CSV 文件,但是我只想导入一些列 我在网络上找到的 link 下面使用了这个脚本。 它可以工作,但它会导入包含所有列和行的完整文件。 我只需要导入几列而不是全部。 例如:第 1 列、第 5 列、第 20 列 有人可以帮助我吗?

https://bionicteaching.com/importing-csv-into-google-sheets-via-google-script/comment-page-1/

我相信你的目标如下。

  • 您想从 URL.
  • 中检索 CSV 数据
  • 您想通过检索特定列将 CSV 数据放入 Google Spreadsheet。
  • 您想使用 Google Apps 脚本实现此目的。
    • 当我看到你问题中 https://bionicteaching.com/importing-csv-into-google-sheets-via-google-script/comment-page-1/ 的 URL 时,我了解到该脚本是 Google Apps Script。
  • 您正在使用 https://bionicteaching.com/importing-csv-into-google-sheets-via-google-script/comment-page-1/ 的脚本。

修改点:

  • 在当前阶段,Utilities.parseCsv()可用于将CSV数据解析为数组。使用此方法时,CSV 数据可以解析为二维数组。我以为这个也许可以用。
  • 为了检索具体的列,我认为可以从CSV数据解析的数组中检索。

以上几点反映到脚本中,就变成了下面的样子。

示例脚本:

请将以下脚本复制并粘贴到 Google Spreadsheet 的脚本编辑器中。并且,请设置变量,运行 myFunction。这样,检索特定列的 CSV 数据将被放入活动 sheet.

function myFunction() {
  // 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 = '###'; // Please set the direct link of CSV data.
  const res = UrlFetchApp.fetch(url);

  // 3. Parse CSV data.
  const ar = Utilities.parseCsv(res.getContentText());

  // 4. Retrieve the required columns from the CSV data.
  const values = ar.map(r => requiredColumns.map(i => r[i]));

  // 5. Put the values to the active sheet.
  const sheet = SpreadsheetApp.getActiveSheet();
  sheet.getRange(1, 1, values.length, values[0].length).setValues(values);
}
  • 如果您的 CSV 数据使用特定的分隔符,请将 const ar = Utilities.parseCsv(res.getContentText()); 修改为 const ar = Utilities.parseCsv(res.getContentText(), "delimiter");Ref

注:

  • 当你想运行这个脚本作为自定义函数时,也可以用下面的脚本。在这种情况下,请将 =SAMPLE("URL","1,5,20") 放入单元格。至此,检索特定列的CSV数据被放入。

      function SAMPLE(url, columns) {
        const requiredColumns = columns.split(",");
        const res = UrlFetchApp.fetch(url);
        return Utilities.parseCsv(res.getContentText()).map(r => requiredColumns.map(i => r[i.trim()]));
      }
    

参考文献:

已添加 1 个:

根据您提供的示例 CSV 数据,我可以了解问题的原因。我认为在这种情况下,对于上述方法,CSV 数据的大小可能很大。据此,我认为可能会发生此类错误。当我检查CSV数据时,发现它有4,763,515个单元格,42,155行和113列。所以,为了解决这个问题,我想建议第二个示例脚本如下。

在本示例中,首先使用Drive API将CSV数据转换为Spreadsheet,然后使用Sheets API删除所需列以外的列,然后,sheet 被复制到活动的 Spreadsheet.

示例脚本:

在您使用此脚本之前,please enable Drive API and Sheets API at Advanced Google services。由于数据量大,我使用了 Drive API 和 Sheets API。

function myFunction2() {
  // 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";  // This is from your sample CSV data.
  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 sheet including CSV data to the active Spreadsheet.
  const dstss = SpreadsheetApp.getActiveSpreadsheet();
  sheet.copyTo(dstss).setName("sheetIncludingCSV");
  
  // 6. Remove the temporat Spreadsheet.
  DriveApp.getFileById(id).setTrashed(true);
}

添加了 2 个:

sorry this sheet.copyTo(dstss); works but it creates me a lot of copy sheet, i need only one sheet with always the same name

根据您的回复,我为此修改了上面的脚本。

示例脚本:

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);
}
  • 此示例脚本将修改后的 CSV 数据放入活动 Spreadsheet 的特定 sheet。
  • 在这种情况下,值是从第 1 行和第 1 列开始的。所以当你想放其他范围时,请修改脚本。