'Export data from the Google Sheet to PDF PYTHON

I am getting all the data present in google sheet using code below, i want to write all these data to the pdf file and download that.

import gspread
import sys 
print(sys.path)
import os
#sys.path.append('/usr/lib/python3/dist-packages')
from oauth2client.service_account import ServiceAccountCredentials

scope = [
'https://www.googleapis.com/auth/spreadsheets',
'https://www.googleapis.com/auth/drive'
]
path = os.path.abspath('cred.json')
credentials=ServiceAccountCredentials.from_json_keyfile_name('cred.json',scope)
client=gspread.authorize(credentials)
sheet=client.open('xyz').sheet1
data=sheet.get_all_records()
print(data)


Solution 1:[1]

I believe your goal as follows.

  • You want to export Google Spreadsheet of xyz as a PDF file using gspread with python and the service acccount.

Modification points:

  • Unfortunately, it seems that in the current stage, the Spreadsheet cannot be directly export as a PDF file using gspread. So in this case, requests library and the endpoint for exporting Spreadsheet to PDF are used.

When the points are reflected to your script, it becomes as follows.

Modified script:

import gspread
import sys 
print(sys.path)
import os
#sys.path.append('/usr/lib/python3/dist-packages')
from oauth2client.service_account import ServiceAccountCredentials

scope = [
'https://www.googleapis.com/auth/spreadsheets',
'https://www.googleapis.com/auth/drive'
]
path = os.path.abspath('cred.json')
credentials=ServiceAccountCredentials.from_json_keyfile_name('cred.json',scope)
client=gspread.authorize(credentials)

# I added below script
spreadsheet_name = 'xyz'
spreadsheet = client.open(spreadsheet_name)
url = 'https://docs.google.com/spreadsheets/export?format=pdf&id=' + spreadsheet.id
headers = {'Authorization': 'Bearer ' + creds.create_delegated("").get_access_token().access_token}
res = requests.get(url, headers=headers)
with open(spreadsheet_name + ".pdf", 'wb') as f:
    f.write(res.content)

Note:

  • In this modified script, it supposes that you hav ealready been able to get values from Google Spreadsheet using Sheets API. Please be careful this.
  • If an error related to Drive API, please enable Drive API at the API console.
  • If an error related to the service account, please modify create_delegated("") to create_delegated("email of the service account").

Solution 2:[2]

The expressions void{}, @as(void, undefined), and {} have type void, for example. You can see {} used in the standard library test cases for std.sort.sort.

Solution 3:[3]

The "canonical" way of getting the void value is to use an empty block.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tanaike
Solution 2 ArborealAnole
Solution 3 kristoff