I have a sheet that has more than 30 charts and my employees need to download all charts every hour, around 24/7 which takes much time for them. so my question is, is there is any way to download all charts in the sheets with one click or in an automated way?
I believe your goal is as follows.
You want to retrieve all charts from all sheets in a Google Spreadsheet.
You want to download all chart images as a PDF file.
From your following replying, I understood like above
> the current issue is that my team is working on hourly performance for the agents and we have many teams and we have charts for performance and quality so the total charts that need to be downloaded and sent to each team are around 30 charts which translates to 30 downloads to each chart image. so this is happening every hour for 24 hours for the whole day which is 24 hours across week, month, year. so imagine if each hour takes 5 minutes to just download this will result in 120 mins or 2 hours a day, in a month this will cost us 14 hours per week, 60 hours per month.
> I know that I can add the charts to Google slides and export them as pdf, but the managers wouldn't prefer that idea that much
But, from your question and replying, I couldn't understand where you want to download the PDF file to? So in this answer, I would like to propose the following 2 patterns.
Download chart images as a PDF to Google Drive.
Download chart images as a PDF to a local PC.
Pattern 1:
In this pattern, the chart images are downloaded as a PDF to Google Drive. Please copy and paste the following script to the script editor of Google Spreadsheet. In this case, when myFunction() is run, the PDF file is downloaded to Google Drive.
function myFunction() {
const outputFilename = "sample.pdf";
// 1. Retrieve all charts in a Google Spreadsheet.
const charts = SpreadsheetApp.getActiveSpreadsheet().getSheets().flatMap(s => s.getCharts());
// 2. Create new Google Slides as a temporal file.
const s = SlidesApp.create("temp");
// 3. Put the charts to each slide.
let slide = s.getSlides()[0];
slide.getShapes().forEach(e => e.remove());
charts.forEach((c, i, a) => {
slide.insertSheetsChart(c).alignOnPage(SlidesApp.AlignmentPosition.CENTER);
if (i < a.length - 1) slide = s.appendSlide();
});
s.saveAndClose();
// 4. Output Google Slides as a PDF data.
const file = DriveApp.getFileById(s.getId());
DriveApp.createFile(file.getBlob().setName(outputFilename));
// 5. Remove the temporal file of Google Slides.
file.setTrashed(true);
}
Pattern 2:
In this pattern, the chart images are downloaded as a PDF to a local PC. This method is from this answer. In this case, when download() is run, the PDF file is downloaded to the local PC using Javascript on the opened dialog.
But, in this pattern, it is required to run the script by the user on browser. Because Javascript is used on the browser. Please be careful this.
Code.gs
Please copy and paste the following script to the script editor of Google Spreadsheet as a script.
function download() {
const html = HtmlService.createHtmlOutputFromFile("index");
SpreadsheetApp.getUi().showModalDialog(html, "sample");
}
function downloadFile() {
const outputFilename = "sample.pdf";
// 1. Retrieve all charts in a Google Spreadsheet.
const charts = SpreadsheetApp.getActiveSpreadsheet().getSheets().flatMap(s => s.getCharts());
// 2. Create new Google Slides as a temporal file.
const s = SlidesApp.create("temp");
// 3. Put the charts to each slide.
let slide = s.getSlides()[0];
slide.getShapes().forEach(e => e.remove());
charts.forEach((c, i, a) => {
slide.insertSheetsChart(c).alignOnPage(SlidesApp.AlignmentPosition.CENTER);
if (i < a.length - 1) slide = s.appendSlide();
});
s.saveAndClose();
// 4. Output Google Slides as a blob of PDF data.
const file = DriveApp.getFileById(s.getId());
const blob = file.getBlob().setName(outputFilename);
// 5. Remove the temporal file of Google Slides.
file.setTrashed(true);
// 6. Return data as base64.
return {data: `data:${MimeType.PDF};base64,${Utilities.base64Encode(blob.getBytes())}`, filename: outputFilename};
}
index.html
Please copy and paste the following script to the script editor of Google Spreadsheet as HTML.
<script>
google.script.run
.withSuccessHandler(({ data, filename }) => {
if (data && filename) {
const a = document.createElement("a");
document.body.appendChild(a);
a.download = filename;
a.href = data;
a.click();
}
google.script.host.close();
})
.downloadFile();
</script>
Note:
The above pattenrs are the simple sample scripts. So please modify them for your actual situation.
References:
getCharts()
insertSheetsChart(sourceChart)- Custom dialogs
Related thread
Download Google Sheet data as JSON from browser through custom menu
Related
I'm starting to learn Django and one of the projects I have chosen for myself is one that has an HTML front page, in which the user inputs some search text and then that calls to an API using Python and Pytrends, then its saves that information as a CSV file.
I'm having a hard time with the next part which is importing that CSV file into another HTML page, where I would like to use my chart.js file to turn it into a graph. I can't figure out how to open up the file and run it inside of javascript. I have tried a static load but it's not opening up the file, just the path to the file. Please let me know if you need to see any other files or know anything else.
async function getData() {
const data = '{% static "interest.csv" %}';
console.log(data.text());
const table = data.split("\n").slice(1);
table.forEach((row) => {
const columns = row.split(",");
const year = columns[0];
const interest = columns[1];
xlabel.push(year);
console.log(year, interest);
});
Over the years on snapchat I have saved lots of photos that I would like to retrieve now, The problem is they do not make it easy to export, but luckily if you go online you can request all the data (thats great)
I can see all my photos download link and using the local HTML file if I click download it starts downloading.
Here's where the tricky part is, I have around 15,000 downloads I need to do and manually clicking each individual one will take ages, I've tried extracting all of the links through the download button and this creates lots of Urls (Great) but the problem is, if you past the url into the browser then ("Error: HTTP method GET is not supported by this URL") appears.
I've tried a multitude of different chrome extensions and none of them show the actually download, just the HTML which is on the left-hand side.
The download button is a clickable link that just starts the download in the tab. It belongs under Href A
I'm trying to figure out what the best way of bulk downloading each of these individual files is.
So, I just watched their code by downloading my own memories. They use a custom JavaScript function to download your data (a POST request with ID's in the body).
You can replicate this request, but you can also just use their method.
Open your console and use downloadMemories(<url>)
Or if you don't have the urls you can retrieve them yourself:
var links = document.getElementsByTagName("table")[0].getElementsByTagName("a");
eval(links[0].href);
UPDATE
I made a script for this:
https://github.com/ToTheMax/Snapchat-All-Memories-Downloader
Using the .json file you can download them one by one with python:
req = requests.post(url, allow_redirects=True)
response = req.text
file = requests.get(response)
Then get the correct extension and the date:
day = date.split(" ")[0]
time = date.split(" ")[1].replace(':', '-')
filename = f'memories/{day}_{time}.mp4' if type == 'VIDEO' else f'memories/{day}_{time}.jpg'
And then write it to file:
with open(filename, 'wb') as f:
f.write(file.content)
I've made a bot to download all memories.
You can download it here
It doesn't require any additional installation, just place the memories_history.json file in the same directory and run it. It skips the files that have already been downloaded.
Short answer
Download a desktop application that automates this process.
Visit downloadmysnapchatmemories.com to download the app. You can watch this tutorial guiding you through the entire process.
In short, the app reads the memories_history.json file provided by Snapchat and downloads each of the memories to your computer.
App source code
Long answer (How the app described above works)
We can iterate over each of the memories within the memories_history.json file found in your data download from Snapchat.
For each memory, we make a POST request to the URL stored as the memories Download Link. The response will be a URL to the file itself.
Then, we can make a GET request to the returned URL to retrieve the file.
Example
Here is a simplified example of fetching and downloading a single memory using NodeJS:
Let's say we have the following memory stored in fakeMemory.json:
{
"Date": "2022-01-26 12:00:00 UTC",
"Media Type": "Image",
"Download Link": "https://app.snapchat.com/..."
}
We can do the following:
// import required libraries
const fetch = require('node-fetch'); // Needed for making fetch requests
const fs = require('fs'); // Needed for writing to filesystem
const memory = JSON.parse(fs.readFileSync('fakeMemory.json'));
const response = await fetch(memory['Download Link'], { method: 'POST' });
const url = await response.text(); // returns URL to file
// We can now use the `url` to download the file.
const download = await fetch(url, { method: 'GET' });
const fileName = 'memory.jpg'; // file name we want this saved as
const fileData = download.body; // contents of the file
// Write the contents of the file to this computer using Node's file system
const fileStream = fs.createWriteStream(fileName);
fileData.pipe(fileStream);
fileStream.on('finish', () => {
console.log('memory successfully downloaded as memory.jpg');
});
So I currently have some CSV formatted data as a string in my JavaScript code as part of a chrome extension. What I need is a button which when clicked will open a new tab with that CSV data loaded in as a Google Sheets document. Basically a "Open in Google Sheets" button. The opened Google sheet document will preferably not be stored in the signed in user's drive (or any drive), but just open a new tab with the CSV file opened.
$("#opnWithSheetsBtn").click((e)=>{
myCSV = $("#userInput").value()
// Code which will open CSV data in new tab using Google Sheets
})
TLDR: I want to create a "Open with Google Sheets" button in a front-end application.
Solution
Taking into account the information that you shared my assumption is the following: you have your CSV data converted into a Javascript object and stringified. Correct me if I am wrong.
If my assumption is right, then, on the HTML button click you would need to run the function provided below. To be able to run this in Apps Scrip you must go to Resources->Advanced Google Services and activate the Sheets API service (as we will be using its method batchUpdate).
This Sheet API function will grant us with a better efficency than compared to using vanilla Apps Script.
function insertCSVinNewSheet(data){
// Use create to create a new Spreadsheet and get its first sheet.
var sheetId = SpreadsheetApp.create('newSpreadSheet').getSheets()[0].getSheetId();
var spreadsheetId = SpreadsheetApp.getActiveSpreadsheet().getId();
// Create the resource to update your sheet
var resource = {
requests: [
{
pasteData: {
data: data,
coordinate: { sheetId: sheetId },
delimiter: ","
}
}
]
};
// Use the Sheet API to make a batch update in the new sheet inserting all our data
Sheets.Spreadsheets.batchUpdate(resource, spreadsheetId);
}
I hope this has helped you. Let me know if you need anything else or if you did not understood something. :)
There's a 2D party fighter game I play (which runs on Adobe AIR and uses As3==S3) that stores all the instruction code in a .swf that is ran when the game is booted up. When the game is booted up, a method called init() is run that loads all the necessary files for the game, which are comprised of swf's and a couple .swz's. There is a file called init.swz which presumably holds all the variables for the game that I desire to document and edit, however I do not know how to open it and edit it.
After searching for the swz file extension online, I've tried opening it in the programs more websites suggest (adobe flash, flash builder, and adobe flex) but none seem to open the file. I did figure out that the game does uncompress the file before reading it presumably as a ByteArray. I opened the game in a hex editor through reading RAM and it displayed the contents in a format that reminds me of XML.
var _loc11_:ByteArray = new ByteArray();
var _loc12_:uint = int(_loc2_.readInt());
var _loc13_:uint = int(_loc2_.readInt());
_loc11_.length = _loc12_;
_loc8_ = 0;
_loc9_ = int(_loc12_);
while(_loc8_ < _loc9_)
{
_loc8_++;
_loc10_ = _loc8_;
_loc14_ = _loc10_ & 7;
_loc15_ = uint(_loc2_.readUnsignedByte());
_loc11_[_loc10_] = _loc15_ ^ _loc4_ & 255;
_loc4_ = uint(_loc4_ << uint(32 - _loc14_)) | uint(_loc4_ >>> _loc14_);
}
_loc11_.uncompress();
Given the above information, is there anyway to be able to access it in a readable format and modify some of it's contents? (Sorry for bad formatting, I'm new to stackoverflow post-wise)
I have written a script within a gsheet that can create a gdoc based on the information in a row in the spreadsheet.
I am then trying to create a PDF of the gdoc that has been generated by the script in the gsheet. I am trying to make this all one seamless function where the gdoc is created with the pertinent information and then a pdf is automatically created as well. However, the PDF generated is always just a blank page.
I am able to add a script to a gdoc that will function correctly and create a pdf version of itself (or another gdoc), but when I run a function from a gsheet, it is always just the blank one-page pdf, Does anybody know why this is happening, or have a solution?
Here is an example of one of the simpler scripts I've tried and works in the gdoc script - obviously when running it from the gsheet I have to know the ID first and then open the gdoc from that.
function convertPDF(docId)
{
var doc = DocumentApp.getActiveDocument();
var docId = doc.getId();
var docFolder = DriveApp.getFileById(docId).getParents().next().getId();
var docblob = DocumentApp.getActiveDocument().getAs('application/pdf');
docblob.setName(doc.getName() + ".pdf");
var file = DriveApp.createFile(docblob);
var fileId = file.getId();
}
Thanks!
Chris