Google sheets last opened time stamp - google-sheets

How do I see the exact time stamp a sheet was opened on Google Sheets? I can see the date it was opened under ‘Last opened by me’ but not the exact time (unless opened today). Thank you

Please take note that this solution will only provide you the datetime you last viewed the file. It will not show you the datetime when another user opened/viewed a Google Sheet file.
Use Drive API v3 (either API explorer or choose your preferred programming language):
Use Files.list() to search for files in your drive. Use the query term to filter your search.
In this example query, I want to get all the files in my drive with Google Sheets mimetype having the file name of 'Copy of Inventory'
Sample Request using API explorer:
q: mimeType = 'application/vnd.google-apps.spreadsheet' and name = 'Copy of Inventory'
fields:files/name, files/id, files/viewedByMeTime
Sample Response using API explorer:
{
"files": [
{
"id": "1-zarWNraQWigfRl6YyjhUpWHEROVaR9BcAxxxxxx",
"name": "Copy of Inventory",
"viewedByMeTime": "2021-05-18T17:12:39.630Z"
}
]
}
You can also do this in Apps Script using Advanced Drive Service which uses Drive API v2.
Note that the file name tag in Drive API v2 is title
Sample Code:
function getSheetViewTime() {
var query = 'mimeType = "application/vnd.google-apps.spreadsheet" and title = "Copy of Inventory"';
Logger.log(query);
var files = Drive.Files.list({q:query});
Logger.log(files.items[0].lastViewedByMeDate)
}
Result:
5:53:14 AM Notice Execution started
5:53:16 AM Info mimeType = "application/vnd.google-apps.spreadsheet" and title = "Copy of Inventory"
5:53:16 AM Info 2021-05-18T17:12:39.630Z
5:53:16 AM Notice Execution completed

Related

Can't copy file and convert mime type with Google Drive Api

I created a new google doc successfully in my drive, but now I wish to change the file type from 'application/msword' to 'application/vnd.google-apps.document'.
I tried to use the answer here to copy the file, but it's not working:
convert a Word doc into a Google doc using the API via nodejs using drive.files.copy convert in v3 of Google Drive API
The code I have is similar to the above question.
After I create the document as msword I am trying to make a simple copy to convert it to a google doc.
drive.files.create({
requestBody: body.requestBody,
fields: 'id',
}, function (err: any, file: any) {
if (err) {
console.error(err);
} else {
drive.files.copy(
{
fileId: file.data.id,
requestBody: { // You can also use "resource" instead of "requestBody".
name: 'copy',
mimeType: "application/vnd.google-apps.document"
}
},
(err, res) => {
if (err) return console.log("The API returned an error: " + err);
console.log(res.data); // If you need, you can see the information of copied file.
}
);
}
the error I'm getting is
Conversion of the uploaded content to the requested output type is not supported.
Any help is appreciated, thanks!
After making some tests with different mime types from Microsoft Office, it looks like the Office editing mode from Google Drive is unable to read blank files and therefore you were getting the error message.
If I am not mistaken, the way Google Drive works to change files formatting is that they need to open the file first in order to read the information and change the formatting. However, in this case Google Drive is recognizing these blank files as corrupted files and is unable to open them using the Office editing mode.
This looks like an expected behavior but could also be considered as a bug from this specific feature. I would recommend you to post your question in the Google Issue Tracker and explain the behavior and testing you have done so far so that you can confirm if this is just expected or a bug from the Office editing mode.
Reference:
Google Drive Office editing mode
Google Issue Tracker

Is there a way to access the Google Docs Summary from Apps Script?

In March 2022, Google announced autogenerated summaries for some documents, alongside the document outline. I'm wondering if there's a way to access these summaries in gas, e.g. via DocumentApp.
Get summary text from Google Document:
In the current stage, in order to retrieve the document summary, you can retrieve it using Drive API as follows.
GET https://www.googleapis.com/drive/v3/files/fileId?fields=description
The sample Google Apps Script is as follows. When you use this, please enable Drive API at Advanced Google services.
const documentId = "###"; // Please set Document ID.
const summary = Drive.Files.get(documentId).description;
console.log(summary)
When this script is run, the summary text of Google Document can be retrieved.
In this case, you can also use Drive service (DriveApp) as follows.
const documentId = "###"; // Please set Document ID.
const summary = DriveApp.getFileById(documentId).getDescription();
console.log(summary)
Set summary text to Google Document:
In order to retrieve the document summary, you can put it using Drive API as follows.
PATCH https://www.googleapis.com/drive/v3/files/fileId
content-type: application/json
{"description": "sample summary text"}
The sample Google Apps Script is as follows. When you use this, please enable Drive API at Advanced Google services.
const documentId = "###"; // Please set Document ID.
const summary = "sample summary";
Drive.Files.patch({description: summary}, documentId);
When this script is run, the summary text can be put to Google Document.
In this case, you can also use Drive service (DriveApp) as follows.
const documentId = "###"; // Please set Document ID.
const summary = "sample summary";
DriveApp.getFileById(documentId).setDescription(summary);
Note:
Unfortunately, in the current stage, I cannot test these scripts for the autogenerated summary in Document. But, I guess that the autogenerated summary might be able to be retrieved by this method.
References:
Files: get
Files: update
getDescription()
setDescription(description)

Link to a specific sheet in published Google Sheet

I see similar questionns has been asked multiple times before, but I cant seem to get them to work. I've also read that Google changed how their URLs are built up, so most of the solutions were deprecated unfortunately.
I'm looking for a link to a specific sheet of a workbook that has been published. I've made a simple workbook to test, and the published link looks like this:
https://docs.google.com/spreadsheets/d/e/2PACX-1vRrmEbjecLvXhbm409pa6JJXZd_ZXTG8Zt6OevIUs5Axq5oxlCZKU0QXk-2lW05HyXJ2B4Bzy3bG-4L/pubhtml
As you can see there is a top menu to change between the sheets, but that doesn't affect the URL.
Is there any way I can get a URL to "Sheet2" directly? Or is that dependant on having the Sheet ID (I'm not the owner of said spreadsheet)?
I believe your goal as follows.
You want to retrieve the values from Sheet2 from the URL of https://docs.google.com/spreadsheets/d/e/2PACX-1vRrmEbjecLvXhbm409pa6JJXZd_ZXTG8Zt6OevIUs5Axq5oxlCZKU0QXk-2lW05HyXJ2B4Bzy3bG-4L/pubhtml.
The owner of this Spreadsheet is not you.
You don't know the Spreadsheet ID and each sheet ID in the Spreadsheet. You know only the URL of https://docs.google.com/spreadsheets/d/e/2PACX-###/pubhtml.
Under above situation, you want to retrieve the direct URL of the sheet 2.
For above goal, how about this answer?
Issue and workarounds:
Unfortunately, in the current stage, it seems that the Spreadsheet ID and each sheet ID cannot be directly retrieved from the URL of https://docs.google.com/spreadsheets/d/e/2PACX-###/pubhtml. I think that this is the current specification. Also I think that this reason might be due to the security. So in order to achieve your goal, it is required to think of the workaround.
In this answer, as a workaround, I would like to achieve your goal using Web Apps created by Google Apps Script. When Web Apps is used, the directlink of Sheet2 can be retrieved.
Flow:
The flow of this workaround is as follows.
Download the Google Spreadsheet as a XLSX data from the URL of https://docs.google.com/spreadsheets/d/e/2PACX-###/pubhtml.
Convert the XLSX data to Google Spreadsheet.
Publish the converted Google Spreadsheet to Web.
Retrieve the URLs of each sheet.
Usage:
Please do the following flow.
1. Create new project of Google Apps Script.
Sample script of Web Apps is a Google Apps Script. So please create a project of Google Apps Script.
If you want to directly create it, please access to https://script.new/. In this case, if you are not logged in Google, the log in screen is opened. So please log in to Google. By this, the script editor of Google Apps Script is opened.
2. Prepare script.
Please copy and paste the following script (Google Apps Script) to the script editor. And please enable Google Drive API at Advanced Google services. This script is for the Web Apps.
function doGet(e) {
const prop = PropertiesService.getScriptProperties();
const ssId = prop.getProperty("ssId");
if (ssId) {
DriveApp.getFileById(ssId).setTrashed(true);
prop.deleteProperty("ssId");
}
const inputUrl = e.parameter.url;
const re = new RegExp("(https?:\\/\\/docs\\.google\\.com\\/spreadsheets\\/d\\/e\\/2PACX-.+?\\/)");
if (!re.test(inputUrl)) return ContentService.createTextOutput("Wrong URL.");
const url = `${inputUrl.match(re)[1]}pub?output=xlsx`;
const blob = UrlFetchApp.fetch(url).getBlob();
const id = Drive.Files.insert({mimeType: MimeType.GOOGLE_SHEETS, title: "temp"}, blob).id;
prop.setProperty("ssId", id);
Drive.Revisions.update({published: true, publishedOutsideDomain: true, publishAuto: true}, id, 1);
const sheets = SpreadsheetApp.openById(id).getSheets();
const pubUrls = sheets.map(s => ({[s.getSheetName()]: `https://docs.google.com/spreadsheets/d/${id}/pubhtml?gid=${s.getSheetId()}`}));
return ContentService.createTextOutput(JSON.stringify(pubUrls)).setMimeType(ContentService.MimeType.JSON);
}
In this case, the GET method is used.
In this script, when the below curl command is run, the Google Spreadsheet is downloaded as a XLSX data, and the XLSX data is converted to Google Spreadsheet. Then, the converted Spreadsheet is published to the web. By this, the direct links of each sheet can be retrieved.
Also, in this script, it supposes that the original Spreadsheet is changed. So if you run the curl command again, the existing Spreadsheet is deleted and new Spreadsheet is created by downloading from the original Spreadsheet. In this case, the URLs are updated.
So if the Spreadsheet is not changed, you can continue to use the retrieved URLs. Of course, you can also directly use the downloaded and converted Spreadsheet.
3. Deploy Web Apps.
On the script editor, Open a dialog box by "Publish" -> "Deploy as web app".
Select "Me" for "Execute the app as:".
By this, the script is run as the owner.
Select "Anyone, even anonymous" for "Who has access to the app:".
In this case, no access token is required to be request. I think that I recommend this setting for your goal.
Of course, you can also use the access token. At that time, please set this to "Anyone".
Click "Deploy" button as new "Project version".
Automatically open a dialog box of "Authorization required".
Click "Review Permissions".
Select own account.
Click "Advanced" at "This app isn't verified".
Click "Go to ### project name ###(unsafe)"
Click "Allow" button.
Click "OK".
Copy the URL of Web Apps. It's like https://script.google.com/macros/s/###/exec.
When you modified the Google Apps Script, please redeploy as new version. By this, the modified script is reflected to Web Apps. Please be careful this.
4. Run the function using Web Apps.
This is a sample curl command for requesting Web Apps. Please set your Web Apps URL.
curl -L "https://script.google.com/macros/s/###/exec?url=https://docs.google.com/spreadsheets/d/e/2PACX-1vRrmEbjecLvXhbm409pa6JJXZd_ZXTG8Zt6OevIUs5Axq5oxlCZKU0QXk-2lW05HyXJ2B4Bzy3bG-4L/pubhtml"
In this case, the GET method is used at Web Apps side. So you can also directly access to the above URL using your browser.
Note:
When you modified the script of Web Apps, please redeploy the Web Apps as new version. By this, the latest script is reflected to the Web Apps. Please be careful this.
In this answer, I thought that you might use this from outside. So I used Web Apps. If you want to directly retrieved from the Google Apps Script, you can also use the following script.
function myFunction() {
const inputUrl = "https://docs.google.com/spreadsheets/d/e/2PACX-1vRrmEbjecLvXhbm409pa6JJXZd_ZXTG8Zt6OevIUs5Axq5oxlCZKU0QXk-2lW05HyXJ2B4Bzy3bG-4L/pubhtml";
const prop = PropertiesService.getScriptProperties();
const ssId = prop.getProperty("ssId");
if (ssId) {
DriveApp.getFileById(ssId).setTrashed(true);
prop.deleteProperty("ssId");
}
const re = new RegExp("(https?:\\/\\/docs\\.google\\.com\\/spreadsheets\\/d\\/e\\/2PACX-.+?\\/)");
if (!re.test(inputUrl)) throw new Error("Wrong URL.");
const url = `${inputUrl.match(re)[1]}pub?output=xlsx`;
const blob = UrlFetchApp.fetch(url).getBlob();
const id = Drive.Files.insert({mimeType: MimeType.GOOGLE_SHEETS, title: "temp"}, blob).id;
prop.setProperty("ssId", id);
Drive.Revisions.update({published: true, publishedOutsideDomain: true, publishAuto: true}, id, 1);
const sheets = SpreadsheetApp.openById(id).getSheets();
const pubUrls = sheets.map(s => ({[s.getSheetName()]: `https://docs.google.com/spreadsheets/d/${id}/pubhtml?gid=${s.getSheetId()}`}));
console.log(pubUrls); // You can see the URLs for each sheet at the log.
}
References:
Web Apps
Taking advantage of Web Apps with Google Apps Script
Advanced Google services
publish a Google Spreadsheet through Google Apps Scripts
Added:
As another workaround, when the original Spreadsheet is often changed, and the number of sheet is constant in the original Spreadsheet, and then, you want to retrieve only values, you can also use the following script. In this script, the URL is not changed even when the script is run again. So you can continue to use the URL.
Sample script:
function myFunction() {
const inputUrl = "https://docs.google.com/spreadsheets/d/e/2PACX-1vRrmEbjecLvXhbm409pa6JJXZd_ZXTG8Zt6OevIUs5Axq5oxlCZKU0QXk-2lW05HyXJ2B4Bzy3bG-4L/pubhtml";
const re = new RegExp("(https?:\\/\\/docs\\.google\\.com\\/spreadsheets\\/d\\/e\\/2PACX-.+?\\/)");
if (!re.test(inputUrl)) throw new Error("Wrong URL.");
const url = `${inputUrl.match(re)[1]}pub?output=xlsx`;
const blob = UrlFetchApp.fetch(url).getBlob();
const prop = PropertiesService.getScriptProperties();
let sheets;
let ssId = prop.getProperty("ssId");
if (ssId) {
const temp = Drive.Files.insert({mimeType: MimeType.GOOGLE_SHEETS, title: "tempSpreadsheet"}, blob).id;
const tempSheets = SpreadsheetApp.openById(temp).getSheets();
sheets = SpreadsheetApp.openById(ssId).getSheets();
tempSheets.forEach((e, i) => {
const values = e.getDataRange().getValues();
sheets[i].getRange(1, 1, values.length, values[0].length).setValues(values);
});
DriveApp.getFileById(temp).setTrashed(true);
} else {
ssId = Drive.Files.insert({mimeType: MimeType.GOOGLE_SHEETS, title: "copiedSpreadsheet"}, blob).id;
Drive.Revisions.update({published: true, publishedOutsideDomain: true, publishAuto: true}, ssId, 1);
prop.setProperty("ssId", ssId);
sheets = SpreadsheetApp.openById(ssId).getSheets();
}
const pubUrls = sheets.map(s => ({[s.getSheetName()]: `https://docs.google.com/spreadsheets/d/${ssId}/pubhtml?gid=${s.getSheetId()}`}));
console.log(pubUrls); // You can see the URLs for each sheet at the log.
}

Get Google Sheets Last Edit date using Sheets API v4 (Java)

I'm using the Google Sheets API v4 in Android.
https://developers.google.com/sheets/api/quickstart/android
I need to know when the last modification to the sheet was made (including by user); I need this guy:
I'd like to do something like this:
Spreadsheet spreadsheet = sheetsService.spreadsheets().get(spreadsheetId).setIncludeGridData(true).execute();
Date date = spreadsheet.getProperties().getLastEditDate();
But, of course, no such getLastEditDate() property method exists. Is there a parameter or another API method to call to get this data?
Even better would be to get the modified date for each cell... but I'd settle for the date of the entire spreadsheet or sheet.
This is not available in the Sheets API, but you may be able to use the Drive API's files.get method, which includes a 'modifiedTime' in the response. (Note that by default it will not include the modified time, you have to explicitly ask for it in the 'fields' parameter.)
It looks like this cannot be done with Sheets API v4.
However...it does look like it can be done with the compatible Google Drive API v3.
Note: the best part about this solution was that I could use the same method of authentication and credential gathering for both APIs. E.g., once I had the code for getting the credentials, I could use it for both API's interchangeably and consecutively.
Here's what I did:
Added this to my build.gradle (shown below my Sheets API declaration)
compile('com.google.apis:google-api-services-sheets:v4-rev468-1.22.0') {
exclude group: 'org.apache.httpcomponents'
}
compile('com.google.apis:google-api-services-drive:v3-rev69-1.22.0') {
exclude group: 'org.apache.httpcomponents'
}
I was already using the EasyPermissions method for getting account and credentials. Great example here.
Then...
import com.google.api.services.drive.Drive;
...
protected Drive driveService = new Drive.Builder(transport, jsonFactory, credential)
.setApplicationName("My Application Name")
.build();
... async:
private DateTime getSheetInformation() throws IOException {
String spreadsheetId = settings.getSpreadsheetId();
Drive.Files.Get fileRequest = driveService.files().get(spreadsheetId).setFields("id, modifiedTime");
File file = fileRequest.execute();
if (file != null) {
return file.getModifiedTime();
}
return null;
}
The sheets api v3 will be deprecated in March 2020, when that happens, your best bet is to use the drive API.
https://developers.google.com/drive/api/v3/reference/files/list
you can pass

uploading a file from iOS mobile application to SharePoint

I'm working on a SharePoint mobile solution where I'm using the web services exposed in server/_vti_bin/sitedata.asmx, server/_vti_bin/Lists.asmx and server/_vti_bin/copy.asmx.
I'm able to successfully fetch the list of sites, document libraries and files using the services defined in server/_vti_bin/sitedata.asmx.
Now I'm actually trying to upload an image file from Photo Albums available in iOS to SharePoint. For this, I tried using CopyIntoItems web service, where in I'm getting the following error response.
<CopyResult ErrorCode="DestinationInvalid" ErrorMessage="The Copy web service method must be called on the same domain that contains the destination url." DestinationUrl="http://xxxxserveripxxxxxx/Shared Documents/image1.png"/>
But came to know that this service is used only if the file to be uploaded is also from the same source(i.e., from sharepoint).
Is there any other way to upload a file available in iPhone to SharePoint.
Also tired addAttachment service defiend in server/_vti_bin/Lists.asmx but I'm unable to identify the input parameters which requires list name and list Item ID.
I'm trying to upload a file to Shared Documents, so I've List Name value which is the one in curly braces of Shared Documents but now what should be the List Item Id value?
These are the details I've with regard to "Shared Documents" document library.
{
AllowAnonymousAccess = false;
AnonymousViewListItems = false;
BaseTemplate = DocumentLibrary;
BaseType = DocumentLibrary;
DefaultViewUrl = "/Shared Documents/Forms/AllItems.aspx";
Description = "Share a document with the team by adding it to this document library.";
InheritedSecurity = true;
InternalName = "{425F837A-F110-4876-98DE-C92902446935}";
LastModified = "2013-07-26 20:09:58Z";
ReadSecurity = 1;
Title = "Shared Documents";
},
So, I'm using the using InternalName value for listName tag.
What should be the value of listItemID?
Am I going in the right way or is there any other approach to upload a local file from mobile to SharePoint?
Thanks
Sudheer
Are you actually calling a URL or are you using the IP (you x'ed it out and said server IP)? If you don't have Alternate Access Mappings defined for the IP, uploads will fail but the GET requests will generally work ok.

Resources