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

Convert Local Excel.xlsx File to Google spreadsheet Google DRIVE API

我正在尝试使用本地 Excel 文件中存在的所有现有设计、格式和公式来转换本地 Excel.xlsx 文件。我如何使用 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,
    ));

但这不起作用。我该如何纠正?

我相信你的目标如下。

  • 您想从本地 PC 上传 XLSX 文件到 Google 文档。
  • 上传 XLSX 文件后,您想将其转换为 Google 电子表格。
  • 您想使用 googleapis 实现此目的 PHP。

修改点:

  • 在您的脚本中,使用了“文件:复制”的方法。此方法复制 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("%s\n", $createdFile->getId());

注:

  • 在此修改后的脚本中,假设您已经能够使用驱动器 API 获取和输出 Google 驱动器的值。请注意这一点。
  • 在此方法中,最大文件大小为 5 MB。请注意这一点。当您想上传大文件时,请使用断点续传。 Ref

参考文献: