Skip to content
Advertisement

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

I am trying to convert a local Excel.xlsx file with all existent design, format and formulas existent in my local Excel file. How can I do that using Google API with PHP? What I was doing but not working was :

    $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,
    ));

But that is not working. How should I correct?

Advertisement

Answer

I believe your goal as follows.

  • You want to upload a XLSX file from the local PC to Google Document.
  • When the XLSX file is uploaded, you want to convert it to Google Spreadsheet.
  • You want to achieve this using googleapis for PHP.

Modification points:

  • In your script, the method of “Files: copy” is used. This method copies the file on Google Drive. So I think that this cannot be used for achieving your goal. I think that this is the reason of your issue.
  • From your error message, I thought that you might be using Drive API v3. I guess that this might be also the reason of your issue.

From above points, when your script is modified, it becomes as follows.

Modified script:

$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());

Note:

  • In this modified script, it supposes that you have already been able to get and out values for Google Drive using Drive API. Please be careful this.
  • In this method, the maximum file size is 5 MB. Please be careful this. When you want to upload the large file, please use the resumable upload. Ref

References:

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement