0

我想以 csv 格式下载 excel 文档的所有工作表。目前,只能访问第一张工作表数据。代码如下:

function downloadGDriveFile (file) {
var request1 = gapi.client.drive.files.export({
  'fileId': '1VLFgD8CNvXTVdHKyBdZPUmgFmhWMzg7qWLbxzLUTtSo',
  'mimeType': 'text/csv'
})
request1.then(function(response) {
  //console.log(response);
}, function(err) {
  console.log('Error');
  console.log(err.result.error);
});
}

目前我正在使用静态 ID。excel给了两张纸。但代码只显示第一张表数据。如何下载工作簿中的所有工作表。

4

1 回答 1

1

我从本教程博客中了解到,这确实是您尝试导出文件时的行为。

但是,有一种方法可以使用 Apps 脚本从电子表格中获取所有工作表。执行自定义菜单“csv->export as csv file”后,工作表将被放置在您的 Google Drive 文件夹内。这是博客中的代码:

function onOpen() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var csvMenuEntries = [{name: "export as csv files", functionName: "saveAsCSV"}];
  ss.addMenu("csv", csvMenuEntries);
};

function saveAsCSV() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheets = ss.getSheets();
  // create a folder from the name of the spreadsheet
  var folder = DriveApp.createFolder(ss.getName().toLowerCase().replace(/ /g,'_') + '_csv_' + new Date().getTime());
  for (var i = 0 ; i < sheets.length ; i++) {
    var sheet = sheets[i];
    // append ".csv" extension to the sheet name
    fileName = sheet.getName() + ".csv";
    // convert all available sheet data to csv format
    var csvFile = convertRangeToCsvFile_(fileName, sheet);
    // create a file in the Docs List with the given name and the csv data
    folder.createFile(fileName, csvFile);
  }
  Browser.msgBox('Files are waiting in a folder named ' + folder.getName());
}

function convertRangeToCsvFile_(csvFileName, sheet) {
  // get available data range in the spreadsheet
  var activeRange = sheet.getDataRange();
  try {
    var data = activeRange.getValues();
    var csvFile = undefined;

    // 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);
  }
} 
于 2017-04-22T17:17:21.940 回答