如何用Google Apps Script导出带自定义页脚的Google Sheet PDF
如何用Google Apps Script导出带自定义居中页脚的PDF
我明白你想通过脚本实现手动导出PDF时的自定义页脚功能——手动操作里的“编辑自定义字段”确实直观,但对应的URL参数藏得比较深,我来给你两种可靠的实现方法:
方法一:利用Google Sheets API设置页脚(更稳定)
这种方法通过API直接修改Sheet的页脚设置,导出后还可以选择恢复原有设置,适合需要长期复用的场景。
步骤1:启用Google Sheets API
- 打开你的Google Apps Script项目
- 点击左侧菜单栏的「服务」→「添加服务」
- 找到「Google Sheets API」并添加
步骤2:编写脚本代码
以下脚本会临时设置居中页脚,导出PDF后再恢复原来的页脚(如果不需要恢复可以去掉恢复部分):
function exportSheetWithCustomFooter() { const spreadsheetId = SpreadsheetApp.getActiveSpreadsheet().getId(); const sheet = SpreadsheetApp.getActiveSheet(); const sheetId = sheet.getSheetId(); // 保存原有页脚设置(可选) const originalFooter = Sheets.Spreadsheets.get(spreadsheetId, { ranges: [`${sheet.getName()}!1:1`], fields: 'sheets/headerFooter' }).sheets[0].headerFooter; // 设置自定义居中页脚 Sheets.Spreadsheets.batchUpdate({ requests: [ { updateHeaderFooter: { headerFooter: { footer: { content: 'My Company Proprietary and Confidential', alignment: 'CENTER' } }, fields: 'footer', sheetId: sheetId } } ] }, spreadsheetId); // 构造导出URL并获取PDF内容 const exportUrl = `https://docs.google.com/spreadsheets/d/${spreadsheetId}/export?format=pdf&gid=${sheetId}`; const token = ScriptApp.getOAuthToken(); const response = UrlFetchApp.fetch(exportUrl, { headers: { 'Authorization': `Bearer ${token}` } }); // 恢复原有页脚(可选) if (originalFooter) { Sheets.Spreadsheets.batchUpdate({ requests: [ { updateHeaderFooter: { headerFooter: originalFooter, fields: '*', sheetId: sheetId } } ] }, spreadsheetId); } // 保存PDF到Google Drive DriveApp.createFile(response.getBlob().setName('Exported_Sheet.pdf')); }
方法二:直接构造包含页脚参数的导出URL(更轻量)
手动导出PDF时,浏览器的网络请求里包含了所有自定义页眉页脚的参数,我们可以直接把这些参数加到导出URL里,不需要修改Sheet本身:
function exportWithFooterUrlParams() { const spreadsheetId = SpreadsheetApp.getActiveSpreadsheet().getId(); const sheetId = SpreadsheetApp.getActiveSheet().getSheetId(); // 编码页脚内容(处理空格和特殊字符) const footerText = encodeURIComponent('My Company Proprietary and Confidential'); // 构造完整的导出URL,包含居中页脚参数 const exportUrl = `https://docs.google.com/spreadsheets/d/${spreadsheetId}/export?` + `format=pdf` + `&gid=${sheetId}` + `&footer_center=${footerText}` + // 核心:居中页脚参数 `&footer_font_size=10` + // 可选:设置页脚字体大小 `&gridlines=false` + // 可选:隐藏网格线 `&portrait=true`; // 可选:纵向打印 // 获取OAuth令牌并下载PDF const token = ScriptApp.getOAuthToken(); const response = UrlFetchApp.fetch(exportUrl, { headers: { 'Authorization': `Bearer ${token}` } }); // 保存到Drive DriveApp.createFile(response.getBlob().setName('Sheet_With_Footer.pdf')); // 可选:让用户直接下载(弹出对话框) // SpreadsheetApp.getUi().showModalDialog( // HtmlService.createHtmlOutput(`<a href="${exportUrl}&token=${token}" target="_blank">点击下载PDF</a>`), // '导出完成' // ); }
关键参数说明
footer_center:设置居中页脚内容,必须URL编码(用encodeURIComponent处理特殊字符)footer_left/footer_right:对应左/右对齐的页脚footer_font_size:自定义页脚字体大小(默认10号)- 基础参数:
format=pdf(指定导出格式)、gid=XXX(指定要导出的Sheet ID)
这两种方法都能实现你要的效果,方法二更简单直接,方法一更适合需要保留原有Sheet设置的场景。
内容的提问来源于stack exchange,提问作者Colin Fennern
相关产品推荐
相关产品推荐

