当前位置:首页 > 未分类 > 正文内容

Convert Excel Files to CSV in Google Drive with Apps Script

ceacer3周前 (05-02)未分类2610

The Google Apps Script uses the Advanced Drive API to covert Microsoft Excel files (XLS, XLSX) into CSV files and saves them into a specific Google Drive folder. The Excel sheets are deleted after the CSV files are saved in Drive.

Also see: Convert Google Sheets to PDF Files

The conversion engine may timeout if you have too many XLS/XLSX files in a Google Drive and in that case, you’d need to include the time check to ensure that the script doesn’t exceed the execution time limit.

function convertXLSFilesToCSV() {
  var oauthToken = ScriptApp.getOAuthToken(),
    sourceFolder = DriveApp.getFolderById(SOURCE_XLS_FOLDER),
    targetFolder = DriveApp.getFolderById(TARGET_CSV_FOLDER),
    mimes = [MimeType.MICROSOFT_EXCEL, MimeType.MICROSOFT_EXCEL_LEGACY];

  /* Written by Amit Agarwal */
  /* email: [email protected]  */
  /* website: www.ctrlq.org */

  for (var m = 0; m < mimes.length; m++) {
    files = sourceFolder.getFilesByType(mimes[m]);

    while (files.hasNext()) {
      var sourceFile = files.next();

      // Re-upload the XLS file after convert in Google Sheet format
      var googleSheet = JSON.parse(
        UrlFetchApp.fetch('https://www.googleapis.com/upload/drive/v2/files?uploadType=media&convert=true', {
          method: 'POST',
          contentType: 'application/vnd.ms-excel',
          payload: sourceFile.getBlob().getBytes(),
          headers: {
            Authorization: 'Bearer ' + oauthToken,
          },
        }).getContentText()
      );

      // The exportLinks object has a link to the converted CSV file
      var targetFile = UrlFetchApp.fetch(googleSheet.exportLinks['text/csv'], {
        method: 'GET',
        headers: {
          Authorization: 'Bearer ' + oauthToken,
        },
      });

      // Save the CSV file in the destination folder
      targetFolder.createFile(targetFile.getBlob()).setName(sourceFile.getName() + '.csv');

      // Delete the processed file
      sourceFile.setTrashed(true);
    }
  }
}

相关文章

How to Automatically Format Google Form Responses in Google Sheets

How to Automatically Format Google Form Responses in Google Sheets

When someone submits a new Google Form response, the form answers are automaticaly added as a new ro...

How to Send Email Reminders for Google Forms Automatically

How to Send Email Reminders for Google Forms Automatically

You are using Google Forms to collect registrations for an upcoming event and would like to send ema...

How to Email Google Sheets Automatically on a Recurring Schedule

How to Email Google Sheets Automatically on a Recurring Schedule

The Email Spreadsheets add-on for Google Sheets can save office workers a ton of time by automating...

How to Sort Google Sheets Automatically with Apps Script

How to Sort Google Sheets Automatically with Apps Script

This Google Spreadsheet on Udemy courses has about 50 sheets, one for each programming language, and...

How to Make Phone Numbers Callable in Google Sheets and Docs

How to Make Phone Numbers Callable in Google Sheets and Docs

This tutorial explains how to make phone numbers clickable within Google Sheets, Slides and Google D...

Formulas in Google Sheets Disappear When New Rows Are Added

Formulas in Google Sheets Disappear When New Rows Are Added

An order form, created in Google Forms, requires customers to provide their full name, the item quan...