通过AppsScript将过滤/查询的GoogleSpreadsheet导出为pdf

时间:2017-03-21 10:54:41

标签: google-apps-script filter

我有一个电子表格,其中包含一些学生当天的数据(姓名,日期,课程,在场,老师)。

我想通过带有2个标准的pdf导出已过滤的列表:

  1. 姓名
  2. 时间范围
  3. 在电子表格中,我可以通过查询过滤。但我不知道如何通过脚本直接导出它。

1 个答案:

答案 0 :(得分:2)

这是通过菜单导出的功能。运行该函数后,它将保存到根驱动器。

var ss = SpreadsheetApp.getActiveSpreadsheet();
function onOpen() {
 
    // Add a menu item based on properties (doesn't work in AuthMode.NONE).
  var items = [
    {name: 'Export', functionName: 'exportToPDF'},
  ];
    ss.addMenu('Export', items);
    }       
    
function exportToPDF() {
var sheetName = "Sheet1";
var pdfName = "My Created PDF "+Date();
var sourceSpreadsheet = SpreadsheetApp.getActive();
var sourceSheet = sourceSpreadsheet.getSheetByName(sheetName);

//Copy whole spreadsheet
var destSpreadsheet = SpreadsheetApp.open(DriveApp.getFileById(sourceSpreadsheet.getId()).makeCopy("tmp_convert_to_pdf"))

//delete redundant sheets
var sheets = destSpreadsheet.getSheets();
for (i = 0; i < sheets.length; i++) {
if (sheets[i].getSheetName() != sheetName){
destSpreadsheet.deleteSheet(sheets[i]);
}
}

var destSheet = destSpreadsheet.getSheets()[0];
//repace cell values with text (to avoid broken references) 
var sourceRange = sourceSheet.getRange(1,1,sourceSheet.getMaxRows(),sourceSheet.getMaxColumns());
var sourcevalues = sourceRange.getValues();
var destRange = destSheet.getRange(1, 1, destSheet.getMaxRows(), destSheet.getMaxColumns());
destRange.setValues(sourcevalues);

//save to pdf
var theBlob = destSpreadsheet.getBlob().getAs('application/pdf').setName(pdfName);
var newFile = DriveApp.createFile(theBlob);

//Delete the temporary sheet
DriveApp.getFileById(destSpreadsheet.getId()).setTrashed(true);

 SpreadsheetApp.getUi().alert('New PDF file created in the root of your Google Drive')
}