Convert the spreadsheet to CSV and upload it to Cloud Storage with Cloud Functions

Target

After hitting the API endpoint, export the data of a specific spreadsheet to CSV and save it in storage.

What to use

procedure

1. Publish the spreadsheet as a web application

Select Tools-> <> Script Editor "from the spreadsheet toolbar to open the Google Apps Script editor. screenshot-script.google.com-2020.05.14-18_55_28.png

Delete the existing code and paste the code below.

code.gs


function doGet(e) {
  var output = ContentService.createTextOutput(createCSV());
  output.setMimeType(ContentService.MimeType.TEXT);
  return output;
}

function createCSV() {
  var sheetName = 'Sheet name';
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName(sheetName);
  var values = sheet.getDataRange().getValues();
  var csv = values.join('\n');
  return csv;
}

Click "Publish"-> "Introduce as Web Application ..." on the toolbar.

You will be asked for the project name, so give it an appropriate name and click "OK".

You will be asked for the settings. Set "Execute the app as:" to "Me (email address)" and "Who has access to the app:" to "Anyone, even anonymous" and click "Deploy". screenshot-script.google.com-2020.05.14-18_46_39.png

The following screen will be displayed. If you access the URL described in "Current web app URL" and the spreadsheet data is displayed in CSV format, it is successful. screenshot-script.google.com-2020.05.14-18_50_52.png

Make a note of this URL as you will use it later.

2. Grant Cloud Storage permission to create objects

Open Service Accounts in IAM and Administration and click Create Service Account to create a service account.

Open Storage and click Create Bucket to create a bucket.

On the bucket list screen, click "Edit bucket permissions"-> "Add member" from the menu to the right of the bucket.

Add the service account you just created to the new member, select the role, select Cloud Storage → Storage Object Administrator, and click Save.

screenshot-console.cloud.google.com-2020.05.14-19_42_16.png

3. Place a script to upload CSV to Cloud Functions

Open Cloud Functions and click Create Function.

Check "Allow unauthorized calls".

screenshot-console.cloud.google.com-2020.05.14-19_50_20.png

Select Python 3.7 for the runtime. Paste the following code into "MAIN.PY" and "REQUIREMENT.TXT".

main.py


import sys
import csv
import codecs
import requests
import os
import tempfile

from google.cloud import storage


def main(request):
    # Spreadsheet Web application URL
    url = '1.URL displayed in'

    # Cloud Storage
    bucket = 'Bucket name'
    dir = 'Direction name'
    fileName = 'csv name'

    # get data
    r = requests.get(url)
    assert r.status_code == requests.codes.ok, "can't read spreadsheet"  # pylint: disable=no-member

    # make file
    _, temp_local_filename = tempfile.mkstemp()
    with codecs.open(temp_local_filename, 'w', 'utf_8') as f:
        f.write(r.text)

    # upload file
    client = storage.Client()
    bucket = client.get_bucket(bucket)
    blob = bucket.blob(f'{dir}/{fileName}')
    blob.upload_from_filename(filename=temp_local_filename)
    return "success"

REQUIREMENT>TXT


astroid==2.4.0
autopep8==1.5.2
cachetools==4.1.0
certifi==2020.4.5.1
chardet==3.0.4
colorama==0.4.3
google-api-core==1.17.0
google-auth==1.14.1
google-cloud==0.34.0
google-cloud-core==1.3.0
google-cloud-storage==1.28.0
google-resumable-media==0.5.0
googleapis-common-protos==1.51.0
idna==2.9
isort==4.3.21
lazy-object-proxy==1.4.3
mccabe==0.6.1
protobuf==3.11.3
pyasn1==0.4.8
pyasn1-modules==0.2.8
pycodestyle==2.5.0
pylint==2.5.0
pytz==2020.1
requests==2.23.0
rsa==4.0
six==1.14.0
toml==0.10.0
urllib3==1.25.9
wrapt==1.12.1

Set "Function to execute" to "main" and click "Create".

screenshot-console.cloud.google.com-2020.05.14-19_51_28.png

After that, click the function name → hit the URL written in the "Trigger" tab and the CSV will be written out and it will be successful.

reference

-How to run Google Spreadsheet as a simple web server and receive WebHook easily -[GAS] Create and save a CSV file from a specific spreadsheet -[Python] Try to work with Cloud Functions and Cloud Storage

Recommended Posts

Convert the spreadsheet to CSV and upload it to Cloud Storage with Cloud Functions
GAE --With Python, rotate the image based on the rotation information of EXIF and upload it to Cloud Storage.
Read CSV file with Python and convert it to DataFrame as it is
Cloud Functions to resize images using OpenCV with Cloud Storage triggers
[pyqtgraph] Add region to the graph and link it with the graph region
How to upload files to Cloud Storage with Firebase's python SDK
Upload and delete files to Google Cloud Storages with django-storage
Convert the result of python optparse to dict and utilize it
Upload file to GCP's Cloud Storage (GCS) ~ Load with local Python
Process the gzip file UNLOADed with Redshift with Python of Lambda, gzip it again and upload it to S3
Convert from PDF to CSV with pdfplumber
[memo] Send table information to GCS with BigQuery Schedule and Cloud Functions
Scrap the published csv with Github Action and publish it on Github Pages
Extract the TOP command result with USER and output it as CSV
Get the number of visits to each page with ReportingAPI + Cloud Functions
Convert files uploaded to Cloud Storage with Cloud Functions (Python) so that they are not garbled in Excel
Upload data to s3 of aws with a command and update it, and delete the used data (on the way)
Scraping tabelog with python and outputting to CSV
Scraping the holojour and displaying it with CLI
Convert DICOM to PNG with Ascending and Descending
I automated job can stamping with selenium and deployed it to Google Cloud Functions, but it was quite difficult
Convert XLSX to CSV on the command line
Convert the cURL API to a Python script (using IBM Cloud object storage)
Read the csv file with jupyter notebook and write the graph on top of it
It is easy to execute SQL with Python and output the result in Excel
I tried to touch the CSV file with Python
Read the csv file and display it in the browser
Convert the image in .zip to PDF with Python
How to convert JSON file to CSV file with Python Pandas
POST the image with json and receive it with flask
Convert PDF of the situation of people infected in Tokyo with the new coronavirus infection of the Tokyo Metropolitan Health and Welfare Bureau to CSV
Convert 202003 to 2020-03 with pandas
POST the image selected on the website with multipart / form-data and save it to Amazon S3! !!
Recursively get the Excel list in a specific folder with python and write it to Excel.
Return the image data with Flask of Python and draw it to the canvas element of HTML
[Python / Ruby] Understanding with code How to get data from online and write it to CSV
Precautions when inputting from CSV with Python and outputting to json to make it an exe
[Python] Change the Cache-Control of the object uploaded to Cloud Storage
Easy to use Nifty Cloud API with botocore and python
[Python] Read the csv file and display the figure with matplotlib
Convert garbled scanned images to PDF with Pillow and PyPDF
How to convert Youtube to mp3 and download it super-safely [Python]
Batch convert all xlsx files in the folder to CSV files
"Deep copy" and "Shallow copy" to understand with the smallest example
Convert video to black and white with ffmpeg + python + opencv
How to upload a file to Cloud Storage using Python [Make a fixed point camera with Raspberry PI # 1]
Convert GRIB2 format weather data that cannot be opened with pygrib to netCDF and visualize it
[Python] What is pip? Explain the command list and how to use it with actual examples
I tried hitting the Google API with Ruby and Python-Make the database a Spreadsheet and manage it with Google Drive
I tried to create serverless batch processing for the first time with DynamoDB and Step Functions
Scraping the list of Go To EAT member stores in Fukuoka prefecture and converting it to CSV
Find the white Christmas rate by prefecture with Python and map it to a map of Japan
Scraping the list of Go To EAT member stores in Niigata prefecture and converting it to CSV
Upload files to Aspera that comes with IBM Cloud Object Storage (ICOS) using SDK (Python version)
Write to csv with Python
Convert SDF to CSV quickly
Determine the date and time format in Python and convert to Unixtime
Made it possible to convert PNG to JPG with Pillow of Python
Repeat with While. Scripts to Tweet and search from the terminal
How to install OpenCV on Cloud9 and run it in Python
After calling the Shell file on Python, convert CSV to Parquet.