我有这个样本Google Spreadsheet。我想创建一个Google Apps脚本函数,以仅将名为“ TargetSheet”的工作表导出到Excel。由于TargetSheet可能具有公式,因此此导出仅包含值非常重要。同样,颜色和格式也很重要。
最终文件应如下所示。
有人建议我使用此代码段导出工作表,但是由于我是Google Apps脚本的入门者,所以我不太了解如何执行此操作。我应该将其复制到我的代码中吗?我应该以某种方式导入吗?并且在让此功能在脚本中工作之后,我假设我需要创建一个函数以使其正常工作。下面看起来像这样吗?
function exportarPlanilha() {
var spreadsheet = SpreadsheetApp.getActiveSheet();
var file = exportSpreadsheetToFile_(spreadsheet, 'xlsx');
return file;
}
TargetSheet
将活动电子表格中的表格()之一导出为XLSX文件。如果我的理解是正确的,那么这个答案呢?请认为这只是几个可能的答案之一。
当我在您的问题中看到URL的示例脚本时,流程似乎如下。
在您的情况下,导出类型为XLSX格式,即常量。因此,我认为该过程成本可以降低一点。因此,修改后的脚本如下。
请复制以下脚本并将其粘贴到电子表格的脚本编辑器中。并请设置exportSheetName
。然后,请exportarPlanilha
在脚本编辑器中运行该函数。显示授权屏幕时,请授权范围。这样,脚本将运行。
function exportarPlanilha() {
const exportSheetName = 'TargetSheet'; // Please set the target sheet name.
// 1. Copy the active Spreadsheet as a tempora Spreadsheet.
const spreadsheet = SpreadsheetApp.getActiveSpreadsheet().copy('tmp');
// 2. Convert the formulas to the texts.
const targetRange = spreadsheet.getSheetByName(exportSheetName).getDataRange();
targetRange.copyTo(targetRange, {contentsOnly:true});
// 3. Delete the sheets except for a sheet you want to export.
spreadsheet.getSheets().forEach(sheet => {
if (exportSheetName != sheet.getName()) spreadsheet.deleteSheet(sheet)
});
// 4. Retrieve the blob from the export URL.
const id = spreadsheet.getId();
const xlsxBlob = UrlFetchApp.fetch(`https://docs.google.com/spreadsheets/export?id=${id}&exportFormat=xlsx`, {headers: {authorization: `Bearer ${ScriptApp.getOAuthToken()}`}}).getBlob();
// 5. Crete the blob as a file.
DriveApp.createFile(xlsxBlob.setName(`${exportSheetName}.xlsx`));
// 6. Delete the temporate Spreadsheet.
DriveApp.getFileById(id).setTrashed(true);
}
如果我误解了您的问题,而这不是您想要的方向,我深表歉意。
绝对出色的答案。其他两个点:(a)我想在函数中设置一个文件夹链接来存储xlsx和文件名,这可行吗?如果要创建一个按钮来运行它,是否可以在按钮中设置这些变量?(b)是否可以将要导出的工作表设置为活动工作表的xlsx,而不是通过工作表名称“ TargetSheet”拉动它?
@abutremutante感谢您的答复。很高兴您的问题得到解决。关于您的其他问题,我可以确认您已经将其发布为新问题。stackoverflow.com/q/60534241/7108653,我也可以确认它已经解决。很高兴您的新问题解决了。