Open String CSV data in Google Sheets - javascript

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. :)

Related

Download all Google sheets charts in one shot?

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

Script File is not executed in PDF file

I am still new to Syncfusion. Currenly I've done a table with a script (document.ready) function to merge the table cells with similar values. The table have been displayed on Google Chrome successfully with my localhost and the columns of the table containing similar values have been merged successfully as well. A function of generating the webpage to PDF works successfully, but the columns of the table displayed on the PDF file do not merge, so I assume that the script file is not rendered in my PDF function.
This is my PDF Function:
private void printpdf()
{
//printpdf
//Initialize HTML to PDF converter
HtmlToPdfConverter htmlConverter = new HtmlToPdfConverter(HtmlRenderingEngine.WebKit);
WebKitConverterSettings settings = new WebKitConverterSettings();
//Set WebKit path
settings.WebKitPath = Server.MapPath("~/QtBinaries");
settings.EnableJavaScript = true;
settings.AdditionalDelay = 5000;
//Assign WebKit settings to HTML converter
htmlConverter.ConverterSettings = settings;
//Get the current URL
string url = HttpContext.Current.Request.Url.AbsoluteUri;
//Convert URL to PDF
Syncfusion.Pdf.PdfDocument document = htmlConverter.Convert(url);
//Save the document
document.Save("Output.pdf", HttpContext.Current.Response, HttpReadType.Save);
}
This is my Script Function on aspx file:
$(document).ready(function () {
-
-
-
};
The webKit rendering engine will preserve the PDF document like how the input HTML file displayed on WebKit (example, safari) based web browsers. So, kindly ensure the preservation of your webpage on WebKit based browser. If it is not possible, kindly share with us the complete HTML file (save the webpage from a web browser and share the complete HTML file with styles, scripts, etc.,) to us. So, that it will be helpful for us to analyze and assist you further on this.
If your web page is rendering properly in the chrome browser, kindly try our latest Blink rendering engine for the conversion. It will preserve the output PDF document like how the input HTML is displayed on chromium-based browsers. Please refer below link for more information,
https://help.syncfusion.com/file-formats/pdf/convert-html-to-pdf/blink
https://www.syncfusion.com/kb/10258/how-to-convert-html-to-pdf-in-azure-using-blink

Download pdf with filled data in acroform - PDFJS

I am integrating PDF JS in my web application with enabled renderIntrectiveForm property. So I am able to edit the form input in PDF, I am able to fill inputs. But the problem is I am not able to download the PDF with filled data.
I searched as much as I can. And I tried so hard to achieve the functionality. I also tried to update annotation manually as in below code in download function. But still, it is downloading the original PDF.
var pdf = PDFViewerApplication.pdfDocument;
var downloadManager = PDFViewerApplication.downloadManager;
pdf.loadingTask.then(function(data){
data.getPage(1).then(function(page){
page.getAnnotations().then(function(annotations){
annotations[1].fieldValue= "New Text"
pdf.getData().then(function(blobData){
var blob = (0, PDFJS.createBlob)(blobData, 'application/pdf');
downloadManager.download(blob, "a.pdf", "a.pdf");
})
})
})
});
I know i can send json to server and then create a new pdf with json(as in https://www.smartformsondemand.org). But I want to do it with client side only.

Creating PDF of a gdoc from a gsheet script

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

Parsing Excel sheet using javascript

I'm using SheetJS in order to parse Excel sheets however I run into the following error:
"Uncaught TypeError: jszip is not a function"
When executing the following code:
var url = "/test-files/test.xlsx";
var oReq = new XMLHttpRequest();
oReq.open("GET", url, true);
oReq.responseType = "arraybuffer";
oReq.onload = function(e) {
var arraybuffer = oReq.response;
var data = new Uint8Array(arraybuffer);
var arr = new Array();
for(var i = 0; i != data.length; i++) arr[i] = String.fromCharCode(data[i]);
var bstr = arr.join("");
var workbook = XLSX.read(bstr, {type: "binary"});
}
oReq.send();
The original code is located here: https://github.com/SheetJS/js-xlsx
Are there any suggestions for an easier implementation of parsing Excel files?
Posting as answer(solution provided in comments worked) in case this might help someone else in the future:
It looks like you're using the src/xlsx.js version of xlsx.js, which is dependent on other source files, like jszip.js.
To fix this, use the dist version of xlsx.js located in dist/xlsx.js
Here is another solution for people who have problem when trying to use Excel file in JavaScript.Instead of reading an Excel file with JavaScript, you could directly use JavaScript in Excel with the help of the Funfun Excel add-in. Basically, Funfun is a tool that allows you to use JavaScript in Excel, therefore you don't need to use write additional code to parse Excel files.
Basically, what you need to do is
1). Insert the Funfun add-in from Office Add-ins store
2). Create a new Funfun or load a sample from Funfun online editor
3). Write JavaScrip code as you do in any other JavaScript editor. In this step, in order to directly use the data from the spreadsheet, you need to write some JSON I/O to make Excel cell reference. The place this value is in Setting-short but this would be just several lines. For example, let's assume we have some data like below in the spreadsheet.
In this case, the JSON I/O value would be:
{
"data": "=A1:E9"
}
Then in the script.js file, you just need to use one single line of code to read this data.
var dataset = $internal.data;
The dataset would be an array, each item would be one row in the spreadsheet. You could check the Funfun documentation for more explanation.
4). Run the code to plot chart
Here is a sample chart that I made using JavaScript(HighChart.js) and Excel data on Funfun online editor. You could check it on the link below. You could also easily load it to your Excel as described in Step2.
https://www.funfun.io/1/edit/5a439b96b848f771fbcdedf0
Disclosure: I'm a developer from Funfun.

Categories