Создайте электронную таблицу Google Диска из локального CSV-файла с помощью API Google Диска


Я пытаюсь загрузить локальный CSV-файл на Google Диск и отобразить его там как электронную таблицу Google. Однако, когда я захожу на свой Google Диск и нажимаю ссылку на свой файл, я могу только загрузить его, а не просматривать в виде электронной таблицы. Я пробовал использовать ?convert=true, но файл не конвертируется. Я также пытался использовать application/vnd.google-apps.spreadsheet в качестве типа mime, но отмечал изменения или получал ответ 400 Bad request.

Когда я щелкаю правой кнопкой мыши файл, я могу выбрать открытие с помощью электронных таблиц Google, которые затем отображаются файл правильно. Я ничего не могу найти об этом в текущей документации в Google, и поиски в Google не очень помогли.

Что я сделал до сих пор, так это создал новую пустую электронную таблицу Google и попытался заполнить ее своим CSV-файлом, но это дает мне 500 Internal Error.

        $file = new Google_DriveFile();
        $file->setTitle('Exported data from ' . $this->event->title);
        $file->setDescription('Exported data from ' . $this->event->title);
        $file->setMimeType( 'text/csv' );

        try {
            $createdFile = $this->drive->files->insert($file, array(
              'data' => $data,
              'mimeType' => 'application/vnd.google-apps.spreadsheet'
            ), array('convert'=>true));

            // Uncomment the following line to print the File ID
            // print 'File ID: %s' % $createdFile->getId();

         $additionalParams = array(
    'newRevision' => false,
    'data' => $data,
    'convert'=>true //no change if this is true or false
);
            $newFile = $this->drive->files->get( $createdFile->getId() );
            $newFile->setMimeType('text/csv');
            $updated = $this->drive->files->update($createdFile->getId(), $newFile, $additionalParams);

            preint_r($updated);
        } catch (Exception $e) {
            print "An error occurred: " . $e->getMessage();
        }

Я просмотрел API для Google Диска, но не нашел ничего полезного. Мне интересно, следует ли мне использовать API электронных таблиц Google или использовать API Google Диска исключительно?

Заранее большое спасибо, Вальдемар

Author: wally, 2013-01-02

3 answers

Попробуйте выполнить следующее. Это из файла: вставьте ссылку в документацию Google, но я добавил параметр преобразования:

/**
 * Insert new file.
 *
 * @param Google_DriveService $service Drive API service instance.
 * @param string $title Title of the file to insert, including the extension.
 * @param string $description Description of the file to insert.
 * @param string $parentId Parent folder's ID.
 * @param string $mimeType MIME type of the file to insert.
 * @param string $filename Filename of the file to insert.
 * @return Google_DriveFile The file that was inserted. NULL is returned if an API error         occurred.
 */
function insertFile($service, $title, $description, $parentId, $mimeType, $filename) {
  $file = new Google_DriveFile();
  $file->setTitle($title);
  $file->setDescription($description);
  $file->setMimeType($mimeType);

  // Set the parent folder.
  if ($parentId != null) {
    $parent = new ParentReference();
    $parent->setId($parentId);
    $file->setParents(array($parent));
  }

  try {
    $data = file_get_contents($filename);

    $createdFile = $service->files->insert($file, array(
      'data' => $data,
      'mimeType' => $mimeType,
      'convert' => true,
    ));

    // Uncomment the following line to print the File ID
    // print 'File ID: %s' % $createdFile->getId();

    return $createdFile;
  } catch (Exception $e) {
    print "An error occurred: " . $e->getMessage();
  }
}
 4
Author: Jay Lee, 2013-01-02 13:36:40

Я пытаюсь использовать приведенный выше код, он не будет работать для меня , он просто остановится после входа в систему

Просто используйте $файл->setmimetype('приложение/vnd.google-приложения.электронная таблица);

$createdFile = $service->files->insert($file, array(
  'data' => $data,
  'mimeType' => 'text/csv',
  'convert' => true,
));

Это сработает для меня

 2
Author: , 2015-05-11 18:54:44

Мне нужно добавить другие параметры, чтобы заставить его работать. 'Тип загрузки'=> 'составная часть'

$createdFile = $service->files->insert($file,array(
'data' => $data,
'mimeType' => 'text/csv',
'convert' => true,
'uploadType' => 'multipart',
));

Теперь это работает.

 1
Author: Pixel, 2015-09-18 10:47:54