将本地Excel.xlsx文件转换为Google电子表格Google DRIVE API



我正在尝试转换一个本地Excel.xlsx文件,该文件包含本地Excel文件中存在的所有设计、格式和公式。我如何使用Google API和PHP来实现这一点?我正在做但没有工作的是:

$client = new Google_Client();
$client->setApplicationName('Name');
$client->setScopes([Google_Service_Drive::DRIVE]);
$client->setAccessType('offline');
$client->setAuthConfig($_SERVER['DOCUMENT_ROOT'] . '/credentials.json');
$service = new Google_Service_Drive($client);
$fileID = '';
$path = $_SERVER['DOCUMENT_ROOT'] . '/includes/files/';
$fileName = 'MAIN.xlsx';//this is the file I want to convert to Google sheet
$filePathName = $path.$fileName;
$mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
$file->setMimeType($mimeType);
$createdFile = $service->files->copy($file, array(
'data' => $filePathName,
'mimeType' => $mimeType,
'convert' => true,
));

但这是行不通的。我应该如何纠正?

我相信你的目标如下。

  • 您想将XLSX文件从本地PC上传到Google文档
  • 上传XLSX文件时,您希望将其转换为Google电子表格
  • 您希望使用适用于PHP的googleapi来实现这一点

修改点:

  • 在您的脚本中;文件:复制;使用。此方法将文件复制到Google Drive上。所以我认为这不能用来实现你的目标。我认为这就是你问题的原因
  • 从您的错误消息中,我认为您可能正在使用驱动器API v3。我想这可能也是你问题的原因

从以上几点来看,当您的脚本被修改时,它会变成如下。

修改的脚本:

$service = new Google_Service_Drive($client); // Please use your $client here.
$path = $_SERVER['DOCUMENT_ROOT'] . '/includes/files/';
$fileName = 'MAIN.xlsx';//this is the file I want to convert to Google sheet
$filePathName = $path.$fileName;
$file = new Google_Service_Drive_DriveFile();
$file->setName('MAIN.xlsx');
$file->setMimeType('application/vnd.google-apps.spreadsheet');
$data = file_get_contents($filePathName);
$createdFile = $service->files->create($file, array(
'data' => $data,
'uploadType' => 'multipart'
));
printf("%sn", $createdFile->getId());

注:

  • 在这个修改后的脚本中,它假设您已经能够使用Drive API获取和输出Google Drive的值。请小心
  • 在这种方法中,最大文件大小为5 MB。请小心。当你想上传大文件时,请使用可恢复上传。参考

参考文献:

  • 上传文件数据
  • 创建文件

最新更新