【问题标题】:google script import only few column with script谷歌脚本只导入少数带有脚本的列
【发布时间】:2021-01-25 19:04:40
【问题描述】:

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

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

【问题讨论】:

    标签: google-apps-script google-sheets import multiple-columns


    【解决方案1】:

    我相信你的目标如下。

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

    修改点:

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

    当以上几点反映到脚本中时,变成如下。

    示例脚本:

    请将以下脚本复制并粘贴到 Google 电子表格的脚本编辑器中。并且,请设置变量,然后运行myFunction。这样,检索特定列的 CSV 数据将被放入活动工作表中。

    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 数据转换为电子表格,并使用 Sheets API 删除除所需列之外的列,然后将工作表复制到活动电子表格中。

    示例脚本:

    在使用此脚本之前,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:

    对不起这张sheet.copyTo(dstss);有效,但它给我创造了很多复印表,我只需要一张总是同名的表

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

    示例脚本:

    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 数据放到活动电子表格的特定工作表中。
    • 在这种情况下,值从第一行第一列开始。所以当你想放其他范围时,请修改脚本。

    【讨论】:

    • 您好,感谢您的回复。我尝试了您的解决方案,但它给了我这个错误 Errore Exception: could not parse text。 myFunction @ Codice.gs:10 我尝试阅读您的所有参考资料,但找不到原因。你能帮助我吗?谢谢
    • @Stefano Linguari 感谢您的回复。我带来的不便表示歉意。在这种情况下,我认为为了正确确认您的问题,需要确认您的 CSV 数据。那么,您能否提供示例 CSV 数据来复制您的问题?根据这些信息,我想确认您的问题并考虑解决方案。如果您能合作解决您的问题,我很高兴。
    • 你可以在这个链接找到我的csv:stanem.it/csv/InnovaCSV.csv谢谢你的支持
    • @Stefano Linguari 感谢您的回复。从您的示例 CSV 数据中,我在答案中又添加了一个示例脚本。你能确认一下吗?如果这不是您期望的方向,我再次道歉。
    • 很棒的作品很棒。谢谢你,谢谢你,谢谢你。我现在唯一的小问题是这个函数创建了一个工作表调用 sheetIncludingCSV,当我第二次启动一个函数时给我这个错误:已经存在一个名为“sheetIncludingCSV”的工作表。有一种方法可以覆盖同一张工作表而不必每次都创建新工作表?再次感谢您的支持
    猜你喜欢
    • 2020-05-19
    • 1970-01-01
    • 1970-01-01
    • 2018-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多