如何使用Google Apps脚本自动下载Google电子表格数据

时间:2013-04-03 06:02:03

标签: javascript google-apps-script

我是使用Google Apps脚本的新手。我想知道我是否可以创建一个备份程序,在每次更改15分钟后自动在csv文件中下载电子表格数据。 我是否必须创建某种cronjob? 我创建了一个以下脚本,它读取当前工作表中的所有数据并创建一个csv文件。

/**
 * Adds a custom menu to the active spreadsheet, containing a single menu item
 * for invoking the readRows() function specified above.
 * The onOpen() function, when defined, is automatically invoked whenever the
 * spreadsheet is opened.
 * For more information on using the Spreadsheet API, see
 * https://developers.google.com/apps-script/service_spreadsheet
 */
function onOpen() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet();
  var entries = [{
    name : "Download Data",
    functionName : "saveAsCSV"
  }];
  sheet.addMenu("Script Center Menu", entries);
};

function saveAsCSV() {
  // Prompts the user for the file name
  var fileName = Browser.inputBox("Save CSV file as (e.g. myCSVFile):");

  // Check that the file name entered wasn't empty
  if (fileName.length !== 0) {
    // Add the ".csv" extension to the file name
    fileName = fileName + ".csv";
    // Convert the range data to CSV format
    var csvFile = convertRangeToCsvFile_(fileName);
    // Create a file in the Docs List with the given name and the CSV data
    DocsList.createFile(fileName, csvFile);
  }
  else {
    Browser.msgBox("Error: Please enter a CSV file name.");
  }
}

function convertRangeToCsvFile_(csvFileName) {
  try {
    var csvFile = undefined;

    var sheet = SpreadsheetApp.getActiveSheet();
    var rows = sheet.getDataRange();
    var numRows = rows.getNumRows();
    var data = rows.getValues();

    // Loop through the data in the range and build a string with the CSV data
    if (data.length > 1) {
      var csv = "";
      for (var row = 0; row < data.length; row++) {
        for (var col = 0; col < data[row].length; col++) {
          if (data[row][col].toString().indexOf(",") != -1) {
            data[row][col] = "\"" + data[row][col] + "\"";
          }
        }

        // Join each row's columns
        // Add a carriage return to end of each row, except for the last one
        if (row < data.length-1) {
          csv += data[row].join(",") + "\r\n";
        }
        else {
          csv += data[row];
        }
      }
      csvFile = csv;
    }
    return csvFile;
  }
  catch(err) {
    Logger.log(err);
    Browser.msgBox(err);
  }
}

我想定期运行此脚本。我该怎么办呢?

1 个答案:

答案 0 :(得分:1)

代码将是相同的。使用只需在电子表格上添加触发器即可。 只需转到脚本编辑器 - &gt;资源 - &gt;所有触发器 并添加一个新的触发器,使其按时间驱动并选择间隔,然后完成。 :)

function saveAsCSV() {
  // Prompts the user for the file name
  var fileName = SpreadsheetApp.getActiveSheet().getSheetName();

  // Check that the file name entered wasn't empty
  if (fileName.length !== 0) {
    // Add the ".csv" extension to the file name
    fileName = fileName + ".csv";

    // Convert the range data to CSV format
    var csvFile = convertRangeToCsvFile_(fileName);
    // Create a file in the Docs List with the given name and the CSV data
    DocsList.createFile(fileName, csvFile);
  }
  else {
    Browser.msgBox("Error: Please enter a CSV file name.");
  }
}

function convertRangeToCsvFile_(csvFileName) {
  try {
    var csvFile = undefined;

    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var sheet = ss.getSheets()[10];
    var rows = sheet.getDataRange();
    var numRows = rows.getNumRows();
    var data = rows.getValues();

    // Loop through the data in the range and build a string with the CSV data
    if (data.length > 1) {
      var csv = "";
      for (var row = 0; row < data.length; row++) {
        for (var col = 0; col < data[row].length; col++) {
          if (data[row][col].toString().indexOf(",") != -1) {
            data[row][col] = "\"" + data[row][col] + "\"";
          }
        }

        // Join each row's columns
        // Add a carriage return to end of each row, except for the last one
        if (row < data.length-1) {
          csv += data[row].join(",") + "\r\n";
        }
        else {
          csv += data[row];
        }
      }
      csvFile = csv;
    }
    return csvFile;
  }
  catch(err) {
    Logger.log(err);
    Browser.msgBox(err);
  }
}