how to use createAndFillWorkbook() in exceljs? - javascript

I followed the documentation
var workbook = createAndFillWorkbook();
and I get this
error Object # has no method 'createAndFillWorkbook'
even if I required exceljs already
var Excel = require("exceljs");
What I wanted to do was to create a report but I am somehow confused on the documentation because it does not say here how to use the createAndFillWorkbook() method it just says here to use it right away.
I referred here in the documentation: https://github.com/guyonroche/exceljs#writing-xlsx

createAndFillWorkbook(); does not mean a function.(maybe pseudo function)
You must create some workbook then fill content.
See below.
// create workbook by api.
var workbook = new Excel.Workbook();
// must create one more sheet.
var sheet = workbook.addWorksheet("My Sheet");
// you can create xlsx file now.
workbook.xlsx.writeFile("C:\\somepath\\some.xlsx").then(function() {
console.log("xls file is written.");
});

var excel = require("exceljs");
var workbook1 = new excel.Workbook();
workbook1.creator = 'Me';
workbook1.lastModifiedBy = 'Me';
workbook1.created = new Date();
workbook1.modified = new Date();
var sheet1 = workbook1.addWorksheet('Sheet1');
var reColumns=[
{header:'FirstName',key:'firstname'},
{header:'LastName',key:'lastname'},
{header:'Other Name',key:'othername'}
];
sheet1.columns = reColumns;
workbook1.xlsx.writeFile("./uploads/error.xlsx").then(function() {
console.log("xlsx file is written.");
});
This is my sample code which works for me.

Related

I need 2 different buttons, to create new folder and create a new PDF in that folder

I've been struggling to build a specific weekly stock system reports. So to give you a basic overview, I have a mastersheet that I want to generate reports from, triggered by an UI button. The first step however is to create a folder for that week to place the PDF's in. I can create the folder, and I can generate the PDF in my root Google Drive folder, but I can't seem to move the PDF anywhere after that. I have attempted to use .moveTo() but I can't get that to work. Does anyone have any advise?
function onOpen(e)
{
SpreadsheetApp.getUi()
.createMenu('Physical')
.addItem('New folder','newFolder')
.addItem('Generate PDF','generatePDF')
.addToUi();
}
function newFolder(){
var today = new Date();
var week = Utilities.formatDate(today, "Europe/Amsterdam", "w"); //need to find a way to minus 1 for the current week
var spreadsheetId = SpreadsheetApp.getActiveSpreadsheet().getId(); //time to create a new folder
var spreadsheetFile = DriveApp.getFileById(spreadsheetId);
var folderId = spreadsheetFile.getParents().next().getId();
var parFolder = DriveApp.getFolderById(folderId)
var destFolder = parFolder.createFolder('Week ' + week);
}
function generatePDF(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var speadsheetFile = ss.getId();
var file = DriveApp.getFileById(speadsheetFile);
var folderId = file.getParents().next().getId();
var pdf = DriveApp.createFile(ss.getBlob())
pdf.moveTo(folderId); //find way to move file either to destination folder or to parent folder
}
Description
These types of situations are hard to test because the circumstances are specific to the OP questioner. However, I believe this will work.
Using the PropertyService Script Properties, store the newly created folderId and then get that id from Script Properties to move the file.
A note of caution, I didn't check for the case if the week changes and a new folder is not created, the pdf will go to the previous week folder.
Regarding creating a button and linking a function to the button see this article Buttons in Google Sheets
Script
function newFolder(){
var today = new Date();
var week = Utilities.formatDate(today, "Europe/Amsterdam", "w"); //need to find a way to minus 1 for the current week
var spreadsheetId = SpreadsheetApp.getActiveSpreadsheet().getId(); //time to create a new folder
var spreadsheetFile = DriveApp.getFileById(spreadsheetId);
var folderId = spreadsheetFile.getParents().next().getId();
var parFolder = DriveApp.getFolderById(folderId);
var folderName = 'Week '+week;
// check if folder already exists
var subFolders = parFolder.getFoldersByName(folderName);
var destFolder = null;
if( subFolders.hasNext() ) {
SpreadsheetApp.getUi().alert("Folder "+folderName+" already exists");
destFolder = subFolders.next();
}
else {
destFolder = parFolder.createFolder(folderName);
}
// store folder id to Script Properties
var props = PropertiesService.getScriptProperties();
props.setProperty("foldeId",destFolder.getId());
}
function generatePDF(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
// get folder id from Script Properties
var folderId = PropertiesService.getScriptProperties("folderId");
if( !folderId ) {
SpreadsheetApp.getUi().alert("Property folderId not found");
return;
}
var pdf = DriveApp.createFile(ss.getBlob())
pdf.moveTo(folderId); //find way to move file either to destination folder or to parent folder
}
Reference
SpreadsheetApp.getUi().alert()
PropetiesService

Import Data From Excel To MySql With Node JS

I want to read excel to save in MySQL database by using NodeJS. I do not know what library to use. I want to be able to read excel based on certain rows and columns. Please help me.
There are many libraries that you can use :
sheetjs/xlsx
excel.js
etc.
There's a great library SheetJS/js-xlsx that provides an API for reading Excel documents.
For example, if you are uploading a file, you'll end up with something like this:
var XLSX = require('xlsx');
function importFromExcel(file) {
var reader = new FileReader();
reader.onload = function (e) {
/* read workbook */
var bstr = e.target.result;
var workbook = XLSX.read(bstr, { type: 'binary' });
/* for each sheet, grab a sheet name */
workbook.SheetNames.forEach(function (workSheetName, index) {
var sheetName = workbook.SheetNames[index];
var workSheet = workbook.Sheets[sheetName];
var excelData = (XLSX.utils.sheet_to_json(workSheet, { header: 1 }));
mapExcelData(excelData); // do whatever you want with your excel data
});
};
reader.readAsBinaryString(file);
}
function mapExcelData(data) {...}

Excel to JSON javascript code?

I want to convert excel sheet data to json. It has to be dynamic, so there is an upload button where user uploads the excel sheet and the data is then converted into json. Could you please provide me the javascript code? I tried SheetJS but couldn't figure out. I would prefer something straight forward :)
I really appreciate your help!
NOTE: Not 100% Cross Browser
Check browser compatibility # http://caniuse.com/#search=FileReader
as you will see people have had issues with the not so common browsers, But this could come down to the version of the browser.. I always recommend using something like caniuse to see what generation of browser is supported... This is only a working answer for the user, not a final copy and paste code for people to just use..
The Fiddle: http://jsfiddle.net/d2atnbrt/3/
THE HTML CODE:
<input type="file" id="my_file_input" />
<div id='my_file_output'></div>
THE JS CODE:
var oFileIn;
$(function() {
oFileIn = document.getElementById('my_file_input');
if(oFileIn.addEventListener) {
oFileIn.addEventListener('change', filePicked, false);
}
});
function filePicked(oEvent) {
// Get The File From The Input
var oFile = oEvent.target.files[0];
var sFilename = oFile.name;
// Create A File Reader HTML5
var reader = new FileReader();
// Ready The Event For When A File Gets Selected
reader.onload = function(e) {
var data = e.target.result;
var cfb = XLS.CFB.read(data, {type: 'binary'});
var wb = XLS.parse_xlscfb(cfb);
// Loop Over Each Sheet
wb.SheetNames.forEach(function(sheetName) {
// Obtain The Current Row As CSV
var sCSV = XLS.utils.make_csv(wb.Sheets[sheetName]);
var oJS = XLS.utils.sheet_to_row_object_array(wb.Sheets[sheetName]);
$("#my_file_output").html(sCSV);
console.log(oJS)
});
};
// Tell JS To Start Reading The File.. You could delay this if desired
reader.readAsBinaryString(oFile);
}
This also requires https://cdnjs.cloudflare.com/ajax/libs/xls/0.7.4-a/xls.js to convert to a readable format, i've also used jquery only for changing the div contents and for the dom ready event.. so jquery is not needed
This is as basic as i could get it,
EDIT - Generating A Table
The Fiddle: http://jsfiddle.net/d2atnbrt/5/
This second fiddle shows an example of generating your own table, the key here is using sheet_to_json to get the data in the correct format for JS use..
One or two comments in the second fiddle might be incorrect as modified version of the first fiddle.. the CSV comment is at least
Test XLS File: http://www.whitehouse.gov/sites/default/files/omb/budget/fy2014/assets/receipts.xls
This does not cover XLSX files thought, it should be fairly easy to adjust for them using their examples.
js-xlsx library makes it easy to convert Excel/CSV files into JSON objects.
Download the xlsx.full.min.js file from here.
Write below code on your HTML page
Edit the referenced js file link (xlsx.full.min.js) and link of Excel file
<!doctype html>
<html>
<head>
<title>Excel to JSON Demo</title>
<script src="xlsx.full.min.js"></script>
</head>
<body>
<script>
/* set up XMLHttpRequest */
var url = "http://myclassbook.org/wp-content/uploads/2017/12/Test.xlsx";
var oReq = new XMLHttpRequest();
oReq.open("GET", url, true);
oReq.responseType = "arraybuffer";
oReq.onload = function(e) {
var arraybuffer = oReq.response;
/* convert data to binary string */
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("");
/* Call XLSX */
var workbook = XLSX.read(bstr, {
type: "binary"
});
/* DO SOMETHING WITH workbook HERE */
var first_sheet_name = workbook.SheetNames[0];
/* Get worksheet */
var worksheet = workbook.Sheets[first_sheet_name];
console.log(XLSX.utils.sheet_to_json(worksheet, {
raw: true
}));
}
oReq.send();
</script>
</body>
</html>
Input:
Output:
The answers are working fine with xls format but, in my case, it didn't work for xlsx format. Thus I added some code here. it works both xls and xlsx format.
I took the sample from the official sample link.
Hope it may help !
function fileReader(oEvent) {
var oFile = oEvent.target.files[0];
var sFilename = oFile.name;
var reader = new FileReader();
var result = {};
reader.onload = function (e) {
var data = e.target.result;
data = new Uint8Array(data);
var workbook = XLSX.read(data, {type: 'array'});
console.log(workbook);
var result = {};
workbook.SheetNames.forEach(function (sheetName) {
var roa = XLSX.utils.sheet_to_json(workbook.Sheets[sheetName], {header: 1});
if (roa.length) result[sheetName] = roa;
});
// see the result, caution: it works after reader event is done.
console.log(result);
};
reader.readAsArrayBuffer(oFile);
}
// Add your id of "File Input"
$('#fileUpload').change(function(ev) {
// Do something
fileReader(ev);
}
#Kwang-Chun Kang Thanks Kang a lot! I found the solution is working and very helpful, it really save my day.
For me I am trying to create a React.js component that convert *.xlsx to json object when user upload the excel file to a html input tag.
First I need to install XLSX package with:
npm install xlsx --save
Then in my component code, import with:
import XLSX from 'xlsx'
The component UI should look like this:
<input
accept=".xlsx"
type="file"
onChange={this.fileReader}
/>
It calls a function fileReader(), which is exactly same as the solution provided.
To learn more about fileReader API, I found this blog to be helpful:
https://blog.teamtreehouse.com/reading-files-using-the-html5-filereader-api
This is my expansion on https://stackoverflow.com/a/52237535/5079799
While it was working/great example, I'm not using an input form, but fetching from a URL and I have other things to do after fething workbook so I needed to wrap the onload into a promise.
See --> adjust onload function to be used with async/await
Here is what I ended up w/
async function Outside_Test(){
var reso = await Get_JSON()
console.log('reso_out')
console.log(reso)
}
async function Get_JSON() {
var url = "http://MyworkbookURL"
var workbook = await Get_XLSX_As_Workbook_From_URL(url)
/* DO SOMETHING WITH workbook HERE */
var first_sheet_name = workbook.SheetNames[0];
/* Get worksheet */
var worksheet = workbook.Sheets[first_sheet_name];
var reso = (XLSX.utils.sheet_to_json(worksheet, {
raw: true
}));
return reso
}
async function Get_XLSX_As_Workbook_From_URL(url) {
const arrayBuffer = await new Promise((resolve, reject) => {
var oReq = new XMLHttpRequest();
oReq.open("GET", url, true);
oReq.responseType = "arraybuffer";
oReq.onload = () => resolve(oReq.response);
oReq.onerror = reject;
oReq.send();
});
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"
});
return workbook
}

Google Scripts - How to call the correct sheet

I´m learning how to use the Google Scripts, I saw a video on the youtube and I wrote this code based on the video. It will be a dashboard, but the problem I have is: In this spreadsheet, I have more than one Sheet. How can I "tell" the code which sheet it would have to check? In my case the Sheet ID is 8.
I think this would be the only "mistake" in the code!
Thanks for helping!
function doGet() {
// Identify the spreadsheet where the data is stored.
var ss = SpreadsheetApp.openById('0AjizIuAuEzaydFlsRDRrTkZSekROaWNZNV9QbjRDdUE')
var data = ss.getDataRange();
// Create all the filters
var clienteFilter = Charts.newNumberRangeFilter().setFilterColumnIndex(1).build();
var pedidoFilter = Charts.newNumberRangeFilter().setFilterColumnIndex(2).build();
var necessidadeFilter = Charts.newCategoryFilter().setFilterColumnIndex(3).build();
var entregaFilter = Charts.newCategoryFilter().setFilterColumnIndex(4).build();
var notaconsultorFilter = Charts.newNumberRangeFilter().setFilterColumnIndex(5).build();
var notaentregadorFilter = Charts.newNumberRangeFilter().setFilterColumnIndex(6).build();
var recomendariaFilter = Charts.newCategoryFilter().setFilterColumnIndex(8).build();
var atencaoFilter = Charts.newCategoryFilter().setFilterColumnIndex(9).build();
var servicosFilter = Charts.newCategoryFilter().setFilterColumnIndex(10).build();
var entregadorFilter = Charts.newCategoryFilter().setFilterColumnIndex(11).build();
// Create all the charts
var pieChart = Charts.newPieChart()
.setDataViewDefinition(Charts.newDataViewDefinition().setColumns([11,6]))
.build();
// Create the dashboard
var dashboard = Charts.newDashboardPanel().setDataTable(data)
.bind([clienteFilter, pedidoFilter, necessidadeFilter, entregaFilter, notaconsultorFilter, notaentregadorFilter, recomendariaFilter, atencaoFilter, servicosFilter, entregadorFilter],[pieChart])
.build();
// Create the webapp and bind together the filters and charts
var app = UiApp.createApplication();
var filterPanel = app.createVerticalPanel();
var chartPanel = app.createHorizontalPanel();
filterPanel.add(clienteFilter).add(pedidoFilter).add(necessidadeFilter).add(entregaFilter).add(notaconsultorFilter).add(notaentregadorFilter).add(recomendariaFilter).add(atencaoFilter).add(servicosFilter).add(entregadorFilter).setSpacing(10);
chartPanel.add(pieChart).setSpacing(10);
// Format the dashboard layout
dashboard.add(app.createVerticalPanel().add(filterPanel).add(chartPanel));
app.add(dashboard);
return app;
}
in your code , ss comes for a spreadSheet object, which is -way of speaking - the "parent" of the included sheets.
This class (spreadsheet object) has a couple of methods to get sheets that are described in the documentation, for example getSheetByName('name of the sheet') or getSheets() which returns an array of sheet objects. In this case you can chose which one you use with getSheets()[number]

Jscript ReadLine() related

Can any one please tell me that we use ReadLine() to read a particular line from a file (.txt). Now I want to read the total content of the file (not only the first line). For that what method I need to use. I googled a lot but I cant get the solution.
My Code is given below:
var ForReading = 1;
var TristateUseDefault = -2;
var fso = new ActiveXObject("Scripting.FileSystemObject");
var newFile = fso.OpenTextFile(sFileName, ForReading, true, TristateUseDefault);
var importTXT = newFile.ReadLine();
This is returning the first line of the .txt file by importTXT variable. Now I want to get the total file content in importTXT.
Any suggestion will be very much helpful for me.
You use the ReadAll method:
var importTXT = newFile.ReadAll();
(Don't forget to close the stream when you are done with it.)
Here: ReadAll (msdn)
I found the example given very poor - for example it did not CLOSE the file, so I added this to the msdn page:
function ReadAllTextFile(filename)
{
var ForReading = 1;
var fso = new ActiveXObject("Scripting.FileSystemObject");
// Open the file for input.
var f = fso.OpenTextFile(filename, ForReading);
// Read from the file.
var text = (f.AtEndOfStream)?"":f.ReadAll(); // this is where it is read
f.Close();
return text;
}
var importTXT = ReadAllTextFile(sFileName);

Categories

Resources