convertXlsxToSheet(fileId, folderId) copies an Excel file (.xlsx or .xls) to a Google Sheet in the target folder, using the Drive advanced service, and returns the new spreadsheet id. The original Excel file is left where it is — move it yourself after a successful convert if you do not want to process it twice.
When to use
- A Drive inbox of uploaded workbooks that should become Sheets
- A weekly drop of
.xlsxreports you need to script against - Any flow that should not depend on a person clicking File → Save as Google Sheets
How to use this snippet
/**
* Convert an Excel file to a Google Sheet in folderId via Drive.Files.copy.
* Supports Drive API v2 (title, parents: [{id}]) and v3 (name, parents: [id]).
* Enable the advanced service: Editor → Services → Drive API, identifier "Drive".
*
* @param {string} fileId
* @param {string} folderId destination folder for the new Sheet
* @return {string} the new spreadsheet id
*/
function convertXlsxToSheet(fileId, folderId) {
if (typeof Drive === 'undefined' || !Drive.Files || !Drive.Files.copy) {
throw new Error('convertXlsxToSheet: enable the Drive advanced service (Editor → Services → Drive API)');
}
var src = DriveApp.getFileById(fileId);
var mime = src.getMimeType();
var xlsx = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
var xls = 'application/vnd.ms-excel';
if (mime !== xlsx && mime !== xls) {
throw new Error('convertXlsxToSheet: file is not an Excel workbook (' + mime + ')');
}
var base = src.getName().replace(/\.xlsx?$/i, '');
var resource;
var params = { supportsAllDrives: true };
if (Drive.Files.insert) {
// Drive API v2: title + parents as objects
resource = { title: base, mimeType: MimeType.GOOGLE_SHEETS, parents: [{ id: folderId }] };
} else {
// Drive API v3: name + parents as id strings
resource = { name: base, mimeType: MimeType.GOOGLE_SHEETS, parents: [folderId] };
}
var copy = Drive.Files.copy(resource, fileId, params);
return copy.id;
}
Example
function convertOne() {
var id = convertXlsxToSheet('EXCEL_FILE_ID', 'FOLDER_ID');
Logger.log('Created ' + id);
}
Notes
- Enable Drive API under Editor → Services. In the advanced service, v2 resources use
titleandparents: [{id: folderId}]. v3 usesnameandparents: [folderId]. The helper detects v2 by the presence ofDrive.Files.insertand builds the resource accordingly.supportsAllDrives: trueis set in both cases. - Conversion is the
mimeType: MimeType.GOOGLE_SHEETSon the copy, not DriveApp. DriveApp can move files but cannot convert Excel to a Sheet by itself. - Non-Excel MIME types throw. The source file is not deleted or moved.
Happy Coding!
