exportSpreadsheetAsXlsx(spreadsheetId, fileName) builds the spreadsheet export URL (format=xlsx), fetches it with ScriptApp.getOAuthToken(), and returns a named .xlsx blob of the whole workbook.
When to use
- Emailing a weekly report as an Excel attachment
- Filing a snapshot of the workbook in Drive
- Anyone who still needs
.xlsx, not a Google Sheet or a PDF of one tab
How to use this snippet
/**
* Export a spreadsheet as a named .xlsx blob.
* Uses the export URL and an OAuth token from ScriptApp.getOAuthToken().
*
* @param {string} spreadsheetId
* @param {string} [fileName] ".xlsx" is appended if missing; default "export.xlsx"
* @return {GoogleAppsScript.Base.Blob}
*/
function exportSpreadsheetAsXlsx(spreadsheetId, fileName) {
var url = 'https://docs.google.com/spreadsheets/d/' + spreadsheetId + '/export?format=xlsx';
var resp = UrlFetchApp.fetch(url, {
headers: { Authorization: 'Bearer ' + ScriptApp.getOAuthToken() },
muteHttpExceptions: true
});
if (resp.getResponseCode() !== 200) {
throw new Error('exportSpreadsheetAsXlsx: export failed (HTTP ' + resp.getResponseCode() + ')');
}
var name = fileName || 'export.xlsx';
if (!/\.xlsx$/i.test(name)) name += '.xlsx';
return resp.getBlob().setName(name);
}
Example
function emailWorkbook() {
var ss = SpreadsheetApp.getActive();
SpreadsheetApp.flush();
var blob = exportSpreadsheetAsXlsx(ss.getId(), 'Weekly-report');
MailApp.sendEmail({
to: 'ops@example.com',
subject: 'Weekly report',
body: 'The workbook is attached as Excel.',
attachments: [blob]
});
}
Notes
- This is the whole workbook, not a single tab. For a PDF of one tab, see Sheet Tab To Pdf Blob.
- Run it once from the editor so the project has spreadsheet (or Drive) scope. The token is only as powerful as the project already is.
- Call
SpreadsheetApp.flush()first if a script just wrote the values the file should contain. - A non-200 response throws. Hidden tabs are included in the workbook export.
Happy Coding!
