从 google 驱动器 api 下载 xls/xlsx 文件

download xls/xlsx file from google drive api

我正在尝试下载 xls 或 xlsx 文件,但出现错误:

{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "fileNotExportable",
    "message": "Export only supports Docs Editors files."
   }
  ],
  "code": 403,
  "message": "Export only supports Docs Editors files."
 }
}

我正在使用 nodejs。是否可以通过 api 下载 xls xlsx 文件?

代码示例:

export function getFileFromStream(auth, fileId, mimeType) {
  const destPath = `/tmp/${fileId}.xls`;
  const dest = fs.createWriteStream(destPath);
  return new Promise(async (resolve, reject) => {
    const drive = google.drive({version: 'v3', auth});
    drive.files.export(
      { fileId, mimeType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'},
      { responseType: 'stream'},
      (errrr, response) => {
          response.data
            .on('end', function() {
            console.log('downloaded')
            })
            .on('error', function(err) {
              console.log('Error during download', err);
            })
            .pipe(dest);
      });
  });
}

files.export method as used in the documentation sample只能用于下载Google个Workspace文档

要下载非 Google 工作区文档,您需要使用 files.get method as in the sample for Download a file stored on Google Drive:

export function getFileFromStream(auth, fileId, mimeType) {
  const destPath = `/tmp/${fileId}.xls`;
  const dest = fs.createWriteStream(destPath);
  return new Promise(async (resolve, reject) => {
    const drive = google.drive({version: 'v3', auth});
    drive.files.get({
      fileId: fileId,
      alt: 'media'
    })
      .on('end', function () {
        console.log('Done');
      })
      .on('error', function (err) {
        console.log('Error during download', err);
      })
    .pipe(dest);
}