Trying to find and import a txt file from desktop - google-apps-script

I am really only used to using VBA for scripting so this is a very new world for me. With that being said I am trying to write a script out that will be able to find a .txt file based on a user input and then import said file from my C: drive into a blanksheet in the workbook. Is this a capability that Apps script has?

Related

How to access and extract data in App Script that is not bound to the code

I am working on a script that is standalone. It collects its baseline data from a google sheet bound to a form. In the form submission, excel documents are uploaded. While I can access the link for the excel document(google downloads the excel into your drive upon submission and inserts the drive link into the google response sheet), I am having difficulty looking into and extracting anything (exact cell values, ranges, indexes, etc) from the excel doc.
I have tried using various functions from the sheets and spreadsheets classes and continue to get errors. Some suggestions I've found say the excel document needs to be converted into a google sheet before the app script can access it, or that app script won't allow you to work with such a document if it is not bound to your script (since that allows you to activate it)(I can't bind the excel doc because it changes upon every new submission of the form).
Has anyone ever compiled a similar code and figured out how to access an unbound, non-google doc?
Let me know if you need error codes or script snippets. I just wasn't sure if this was a syntax problem or a google suite trick spot that needed extra code that I probably haven't found cause I'm new to this platform.
From the question
Has anyone ever compiled a similar code and figured out how to access an unbound, non-google doc?
Scripts in Google Apps Script aren't "compiled" by the script writer in the sense that it's done when developing something in other platforms.
To get data from a file hosted in Google Drive, first the script should get that file by using the Drive Service (Class DriveApp) or the Drive Advanced Service.
The next part depends pretty much on the Excel file format. If it's an xlsx file, then usually the most convenient is to convert the file into an Google spreadsheet as this will make possible to use the Spreadsheet Service (Class SpreadsheetApp) to read the data from it.
If you don't want to convert it to a Google spreadsheet file, or it can't be converted the the "basic" means because it's using an incompatible format (like a xls file format), then you will need to use an library or an external service to parse the Excel file content.
function getalldataonsheet() {
const ss=SpreadsheetApp.openById('ssid');//you provide id
const sh=ss.getSheetByName('sheetname');//you provide sheet namme
const rg=sh.getDataRange();
const vs=rg.getValues();//2d array
return vs;//this return 2d array
}
There are restrictions for passing parameters in client to server communication

Read file from drive in google colab

I Have read the notebook about how to open drive. I already did as instructed using:
from google.colab import drive
drive.mount('/content/drive')
After this, I can use !ls to list the contents of my drive but I cannot read or open any file. I already tried:
with open("/content/drive/My Drive/filename.ext", "r") as file:
file = open("/content/drive/My Drive/filename.ext", "r")
!cp "/content/drive/My Drive/filename.ext" "filename.ext"
and also
import pandas as pd
file = pd.read_csv("/content/drive/My Drive/filename.ext")
But none of the above worked. I always get "operation not supported" or "cannot open file for reading".
I have seen some suggestin to use PyDrive. But it is done by copy file from Google Drive to Google Drive. I don't get why you would have to copy back and forth files, since I need to iterate over all the files on the folder.
Why can't google colab just read the file stored on drive? Or am I doing something wrong? Another thing is that I uploaded a bunch of csv files, but google drive lists them as ".csv.gsheet" (using glob). Could that be the problem? I have no other ideas.
It is straight forward.
from google.colab import drive
drive.mount('/content/drive')
This will ask to open a url which will authorize the mount after you copy paste the token.
If you are not able to read files even now, then prefix your file path with this: 'drive/My Drive' and you are good to go.
For example: file = 'drive/My Drive/data/file.txt'
Where data is a directory in my Google Drive containing file.txt file.
I ran into a similar issue last night. As some of the previous responders posted there are concerns that influence your ability to read the file. These concerns are, one, making certain that your file is accessible via google drive from your Collab notebook and also, two, making certain that your file is in the correct format.
I will explain the steps and include a screen shot.
Open Google Collab. Open the File Browser.
Click the icon that says Mount Drive when hovered. This inserts a new cell in your notebook with the code:
from google.colab import drive
drive.mount('/content/drive')
Run the cell. You are prompted to accept permissions and get a token to use to mount the drive. Grant the permissions and copy and paste the code into the text input. Hit enter.
The drive now appears in the file browser. Right click the folder /drive/My Drive or click the three dots action menu and select Upload.
Locate your file on disk and Upload.
The file appears in the File Browser. Right click the File (or use the three dots action menu) and select Copy Path.
Paste that file path into your pd.read_csv() call.
Run the cell with the pd.read_csv function call.
You should now have the file uploaded in your Google Drive. Accessible to google collab and file formatting preserved because it not been accessed by any other program to munge the format.
Below is the example sans Permission tab because I previously granted permissions.
I just tried mounting and creating a Drive file as you described and couldn't reproduce the error you describe.
https://colab.research.google.com/drive/17iiKJPQOPv1eW5-Ctf707mPHXDtipE5G
Perhaps try resetting your backend using the Runtime -> Reset all runtimes menu. Or, can you share a notebook illustrating the problem?
I (partially) found out what was going on based on Bob Smith and Ami F's answers.
I believe google drive blocks read access from files converted to drive formats (gsheet, gdoc, etc.). And so, whenever I tried to use !cat or open, I got an "operation unsupported" error. When I tried Bob's example, creating a file and then reading it, it worked on my notebook.
So I managed to prevent google from converting files, deleted the old files and uploaded everything to drive again. Now, all my csv's were being kept unchanged (no .gsheet extesion) and I am able to access them using open.
The fact that you see ".csv.gsheet" filenames even though you upload ".csv" filenames makes me think that you're uploading your CSVs to sheets.google.com instead of drive.google.com. Can you confirm that uploading to drive.google.com makes things work?
I do suspect RenatoSz's answer is correct: I can open XLSX files fine, but even just file = open('name_of_file.gsheet') fails for me with Operation not supported error. Annoying that you cannot do the simple action of opening a Google Sheet in Google Colab - this seems like basic functionality.
A workaround for me was:
from google.colab import auth
auth.authenticate_user()
import gspread
from oauth2client.client import GoogleCredentials
# authorise
gc = gspread.authorize(GoogleCredentials.get_application_default())
# open
gsheets = gc.open_by_url('some_fun_URL')
# read
sheets = gsheets.worksheet('List of all experts').get_all_values()
# parse
df = pd.DataFrame(sheets[1:], columns=sheets[0])
Note that gc.open(...) did not work for me.
You can avoid this problem by the following steps
Upload the dataset(.csv) to google drive.
Now select the uploaded dataset on google drive and select the share option from the drop down menu acquired by making a left-click on the selected file.
Now a pop-up window appears on the screen, change the sharing setting to editor.
And in the bottom left of the pop-up window change the restricted(Only-added can edit) to "Anyone with the link can edit.
After these settings are saved. Copy the generated sharable link.
Now got to the below mentioned website and convert your link by pasting the priorly copied link and generate the google drive downloadable link.
https://sites.google.com/site/gdocs2direct/
Copy the generated google drive downloadable link.
We are ready with the perfect path address now for the dataset.
file = open("Paste Here the Generated link which we copied", "r")
This would sort the issue perfectly.
The same would work even if was a .txt file as well.

Download a file from a link on another site?

I am attempting to use Google Apps Script to download an excel file that is linked to on a CRM. That is, instead of each day having a person log in to the CRM, download new data as an excel file, and copy and paste the new data to our existing Google Sheet, I would like to have my script do so.
Is it possible to do this? I have been looking at UrlFetchApp, however I'm having trouble because there is no direct link to the file I need (only a link to generate and download the file).

Import JSON data into single cell in google sheets

I am wondering if anyone can give me an example on how to gather data from a JSON file, and import it into a single cell in google sheets? It does not need to be formatted or copied to multiple cells, it simply needs to take the entire contents of the JSON and copy it into a single cell. The file I am working with is also a local file. Can anyone shed some light? It does not necessarily need to use google apps script, if a python script or anything similar could do the same thing that would be ok
First of all, Google Sheets cannot access your local files. It's a web application, so any external data it gets must be accessible from the Internet.
If your goal is simply to put the contents of a web-accessible JSON file in a single cell, the following custom function will do the job:
function import(url) {
return UrlFetchApp.fetch(url).getContentText();
}
This simply grabs whatever page you point at, and crams its contents in a cell. Example: =import("http://xkcd.com/info.0.json")
If you do decide to parse JSON, be advised there isn't anything suitable built into Google Sheets at present. The project importJSON by Trevor Lohrbeer may be helpful.
You can also use an extension of "API CONNECTOR" for free in the google sheets and just paste the url of the json file you need to import.
here is the link to the API Connector extension
https://workspace.google.com/marketplace/app/api_connector/95804724197
here is how to perform it.
https://www.benlcollins.com/apps-script/api-tutorial-for-beginners/

Import data from a non public CSV into Google Sheets

I have a list of customer names i would like to import into my spreadsheet from a CSV file. Preferably every hour.
The IMPORTDATA function works fantastic for this kind of operation.
The problem is that i don't want to store a CSV file with peoples names publicly. What would be your best suggestion to importing a CSV file to Google sheets without storing it on a publicly accessible URL? As i understand it there's no way to get Google Sheets to work via FTP?
You could store it in your own Google Drive.
From there you could handle the import with Apps Script instead of import range