📋Convert Excel Files to CSV in Google Drive with Apps Script

1. Overview

\[ \begin{array}{l} \textbf{You can convert Excel files in Google Drive to CSV format automatically --} \\ \text{using Google Apps Script to open, read, and export spreadsheet data.} \\ \textbf{This is useful for integrating Excel data into systems that require CSV --} \\ \text{and for automating repetitive file conversions.} \end{array} \]

2. Core Steps

\[ \begin{array}{ll} \mathbf{Step\ 1:} & \text{Upload your Excel (.xls, .xlsx) files into Google Drive.} \\ \mathbf{Step\ 2:} & \text{Open a Google Spreadsheet or new Apps Script project.} \\ \mathbf{Step\ 3:} & \text{Write a script to search for Excel files in Drive.} \\ \mathbf{Step\ 4:} & \text{Convert each file to Google Sheets format using Drive API.} \\ \mathbf{Step\ 5:} & \text{Export the converted file’s data as a CSV string.} \\ \mathbf{Step\ 6:} & \text{Save the CSV file back into Drive.} \\ \mathbf{Step\ 7:} & \text{(Optional) Move original Excel files to an archive folder.} \end{array} \]

3. Sample Google Apps Script


// Code.gs
function convertExcelToCSV() {
  var folder = DriveApp.getFolderById('YOUR_FOLDER_ID');
  var files = folder.getFilesByType(MimeType.MICROSOFT_EXCEL);
  
  while (files.hasNext()) {
    var file = files.next();
    
    // Convert to Google Sheets
    var convertedFile = Drive.Files.copy(
      { title: file.getName(), mimeType: MimeType.GOOGLE_SHEETS },
      file.getId()
    );
    
    // Open as Sheet
    var ss = SpreadsheetApp.openById(convertedFile.id);
    var sheet = ss.getSheets()[0];
    var data = sheet.getDataRange().getValues();
    
    // Convert data to CSV string
    var csv = data.map(function(row) {
      return row.map(String).join(",");
    }).join("\n");
    
    // Save CSV file in Drive
    folder.createFile(file.getName() + ".csv", csv, MimeType.CSV);
  }
}

4. Important Notes

\[ \begin{array}{l} \text{β€’ You must enable the Advanced Drive Service (Drive API) in Apps Script.} \\ \text{β€’ The script assumes all Excel files are in a specific Drive folder.} \\ \text{β€’ Large Excel files may take longer to process; consider batch processing.} \\ \text{β€’ The CSV file will contain plain text only β€” no formatting is preserved.} \\ \text{β€’ You can add date/time stamps to filenames to prevent overwriting.} \end{array} \]

5. Conceptual Flow (in LaTeX)

The process can be described as:

\[ \text{Excel File in Drive} \xrightarrow{\text{Convert to Google Sheets}} \xrightarrow{\text{Export to CSV}} \text{CSV File in Drive} \]

Where: \[ \text{CSV Output} = \{\text{All Cell Values from Sheet 1, Comma-Separated}\} \]