How to write array in excel sheet using excel4node - node.js

I am creating an excel file by using Excel4node package.
by using this code
// Require library
var excel = require('excel4node');
// Create a new instance of a Workbook class
var workbook = new excel.Workbook();
// Add Worksheets to the workbook
var worksheet = workbook.addWorksheet('Sheet 1');
var worksheet2 = workbook.addWorksheet('Sheet 2');
// Create a reusable style
var style = workbook.createStyle({
font: {
color: '#FF0800',
size: 12
},
numberFormat: '$#,##0.00; ($#,##0.00); -'
});
// Set value of cell A1 to 100 as a number type styled with paramaters of style
worksheet.cell(1,1).number(100).style(style);
// Set value of cell B1 to 300 as a number type styled with paramaters of style
worksheet.cell(1,2).number(200).style(style);
// Set value of cell C1 to a formula styled with paramaters of style
worksheet.cell(1,3).formula('A1 + B1').style(style);
// Set value of cell A2 to 'string' styled with paramaters of style
worksheet.cell(2,1).string('string').style(style);
// Set value of cell A3 to true as a boolean type styled with paramaters of style but with an adjustment to the font size.
worksheet.cell(3,1).bool(true).style(style).style({font: {size: 14}});
workbook.write('Excel.xlsx');
by using this code creating an excel sheet now what I want is.
I want to write the array in the excel sheet.
worksheet.getCell('A1').value = 's.no';
by using the code. it is writing the data to the sheet but it is writing the data by cell by cell.
it takes to much of time to write the array in excel sheet
data=[{s.no:1,Name:'xxx',Age:'22'},
{s.no:2,Name:'yyy',Age:'12'},
{s.no:3,Name:'zzz',Age:'32'}]
I want to write the array in the excel sheet.
workbook.write('Excel.xlsx',data);
I given like this but this also not working.
can anyone resolve this.

why you don't use
sheet.cell(row , col ).string(`your value`).style(`your style`);

What I would do is create an excel4node layer. Something to the effect of:
// the type arg is the cell write method you want to use such as string, number, or formula
const writeCell(wb, ws, row, col, value, type, style){
ws.cell(row, col)[type](value).style(wb.createStyle(style))
}
const xl = require('excel4node')
const wb = xl.createWorkbook()
// TODO: track your row and column indices with arrays. let's assume that we are
// in the outer array and the inner array or row array is called "data"
// this would write out a row of data
data.forEach((d, idx) => {
writeCell(wb, ws, rowIdx, idx + 1, d.value, d.type, d.style)
}

const array_elements = [{
fullname: "name 1",
game1point: 10,
game2point: 12
},
{
fullname: "name 2",
game1point: 15,
game2point: 17
},
]
let startRow = 3;
for (let i = 0; i < array_elements.length; i++) {
// FULLNAME - FIRST COLUMN
worksheet.cell(startRow + i, 1).string(array_elements[i].fullname);
// SECOND COLUMN
worksheet.cell(startRow + i, 2).number(array_elements[i].game1point);
// THIRD COLUMN
worksheet.cell(startRow + i, 3).number(array_elements[i].game2point);
gameCol++;
}

Related

match single cell value with column of values for every match return those rows Google-apps-script

I have a spreadsheet with 2 tabbed sheets. I am trying to run a macro so that when the user inputs a name in B2 of the 2nd sheet, it is matched with every instance of that name in the 1st sheet, column B. I then need to copy all of the data that appears in the matched cell's rows and have that pasted in the 2nd sheet starting with cell B3.
I have limited experience with VBA, but none with JS/Google-apps-script. Any help with how to write this would be greatly appreciated! Here is my first shot:
function onSearch() {
// raw data sheet
var original = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Form Responses 2");
// search for student sheet
var filtered = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Student Progress Search");
// retrieving the values in the raw data array of names
var searchColumn = 2;
var lr = original.getLastRow();
var searchRange = original.getRange(2,searchColumn, lr, 1).getValues();
// retrieving the name submitted on search
var inputName = filtered.getRange(2, 2).getValue();
// loop through all the names in the raw data and identify any matches to the search name
for (var i = 0; i < lr; i++){
var dataValue = searchRange[i];
var r = dataValue.getRow();
var line = [[r]];
var paste = filtered.getRange(3, 3);
// if the data is a match, return the value of that cell in the searched sheet
if (dataValue == inputName){ return paste.setValues(line);
}
}
}
Not sure if the built-in QUERY function would work for you. This here does exactly what you are looking for:
=QUERY(Sheet1!B:B,"select B where LOWER(B) like LOWER('%" &B2& "%')")
For example, if a user enters 'joe', the function will match any entry containing 'joe', regardless of case.

Make an Entire Cell in a MigraDoc Table a Link

Is there a way in MigraDoc to make an entire table cell a link? I have a tabular table of contents, and the page number is difficult to click. I would prefer if the entire cell was clickable to navigate to a specified page. Here is an example of my code:
// Create the table within the document
var document = new Document();
var section = document.AddSection();
var table = section.AddTable();
// Create a column in the table
var column = table.AddColumn();
column.Width = "2cm";
// Create a row in the table
var row = table.AddRow();
row.Height = "1cm";
// Add a hyperlink to the appropriate page
var paragraph = row.Cells[0].AddParagraph();
var hyperlink = paragraph.AddHyperlink("MyBookmarkName");
hyperlink.AddPageRefField("MyBookmarkName");
...
// Create the bookmark later in the document
I'm afraid there is no easy way to make the whole cell clickable. I haven't tried it myself, but you can add images (visible or transparent) or text to the hyperlink.
This will make the clickable area bigger - and if you use e.g. blue underlined text there will be a visual hint that the text is clickable.
I was inspired by the answer from the PDFsharp Team to try and fill the cell with a blank hyperlink image, with text over the hyperlink. Since my ultimate goal was to actually make an entire row a hyperlink, I came up with the following solution.
First, add an additional zero-width column prior to the first column in the table that you want to be a hyperlink. Next, add a paragraph, hyperlink, and transparent 1-pixel image to each zero-width cell. Specify the image height and width to fill however many table cells you want to be a link. Also, be sure to set the font size of the paragraph containing the link to nearly zero (zero throws an exception, but images are aligned on the font baseline, so you need a very small number to prevent the paragraph from being larger than the image).
Note that a zero-width column, even with borders, does not change the apparent border width when viewing the resulting PDF. The following code illustrates my approach:
// Declare some constants
var _rowHeight = new Unit(.75, UnitType.Centimeter);
// Create the document, section, and table
var document = new Document();
var section = document.AddSection();
var table = section.AddTable();
// Format the table
table.Rows.Height = _rowHeight;
table.Rows.VerticalAlignment = VerticalAlignment.Center;
// Define the column titles and widths
var columnInfos = new[] {
new { Title = "Non-Link Column", Width = new Unit(8, UnitType.Centimeter) },
new { Title = "" , Width = new Unit(0 ) },
new { Title = "Link Column 1" , Width = new Unit(8, UnitType.Centimeter) },
new { Title = "Link Column 2" , Width = new Unit(8, UnitType.Centimeter) },
};
// Define the column indices
const int colNonLink = 0;
const int colHyperlink = 1;
const int colLink1 = 2;
const int colLink2 = 3;
// Create all of the table columns
Unit tableWidth = 0;
foreach (var columnInfo in columnInfos)
{
table.AddColumn(columnInfo.Width);
tableWidth += columnInfo.Width;
}
// Remove the padding on the link column
var linkColumn = table.Columns[colHyperlink];
linkColumn.LeftPadding = 0;
linkColumn.RightPadding = 0;
// Compute the width of the summary links
var linkWidth = tableWidth -
columnInfos.Take(colHyperlink).Sum(ci => ci.Width);
// Create a row to store the column headers
var headerRow = table.AddRow();
headerRow.Height = ".6cm";
headerRow.HeadingFormat = true;
headerRow.Format.Font.Bold = true;
// Populate the header row
for (var colIdx = 0; colIdx < columnInfos.Length; ++colIdx)
{
var columnTitle = columnInfos[colIdx].Title;
if (!string.IsNullOrWhiteSpace(columnTitle))
{
headerRow.Cells[colIdx].AddParagraph(columnTitle);
}
}
// In the real code, the following is done in a loop to dynamically add rows
var row = table.AddRow();
// Populate the row header
row.Cells[colNonLink].AddParagraph("Not part of link");
// Change the alignment of the link cell
var linkCell = row.Cells[colHyperlink];
linkCell.VerticalAlignment = VerticalAlignment.Top;
// Add a hyperlink that fills the remaining cells in the row
var linkParagraph = linkCell.AddParagraph();
linkParagraph.Format.Font.Size = new Unit(.001, UnitType.Point);
var hyperlink = linkParagraph.AddHyperlink("MyBookmarkName");
var linkImage = hyperlink.AddImage("Transparent.gif");
linkImage.Height = _rowHeight;
linkImage.Width = linkWidth;
// Populate the remaining two cells
row.Cells[colLink1].AddParagraph("Part of link 1");
row.Cells[colLink2].AddParagraph("Part of link 2");
// Add a border around the cells
table.SetEdge(0, 0, columnInfos.Length, table.Rows.Count,
Edge.Box | Edge.Interior, BorderStyle.Single, .75, Colors.Black);
The result of the above code is a document containing a table with 2 rows, 3 visible columns, where the entirety of the last two cells in the final row are a hyperlink to "MyBookmarkName". Just for reference, I did modify the PDFSharp source code according to the advice here to remove borders around hyperlinks, which looked wonky at certain zoom levels in Adobe Acrobat Reader.

Find value on any sheet in spreadsheets using Google Script

Using the code below I'm able to look through multiple sheets in a spreadsheet to find the first value that equals the selected cell. The only problem with this bit is: The cell with the value found is highlighted yellow, but the cell with the value found isn't selected. See code below for hopping through sheets. I can't get my head around this :)
Funny thing is that the code for highlighting and selecting a value does work when I'm not hopping through the list of sheets, see the best answer: Find value in spreadsheet using google script
function SearchAndFind() {
//determine value of selected cell
var sh = SpreadsheetApp.getActiveSpreadsheet();
var ss = sh.getActiveSheet();
var cell = ss.getActiveCell();
var value = cell.getValue();
//create array with sheets in active spreadsheet
var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
//loop through sheets to look for value
for (var i in sheets) {
//Set active cell to A1 on each sheet to start looking from there
SpreadsheetApp.setActiveSheet(sheets[i])
var sheet = sh.getActiveSheet();
var range = sheet.getRange("A1");
sheet.setActiveRange(range);
//set variables to loop through data on each sheet
var activeR = cell.getRow()-1;
var activeC = cell.getColumn()-1;
var data = sheets[i].getDataRange().getValues()
var step = 0
//loop through data on the sheet
for(var r=activeR;r<data.length;++r){
for(var c=activeC;c<data[0].length;++c){
step++
Logger.log(step+' -- '+value+' = '+data[r][c]);
if(data[r][c]==''||step==1){ continue };
if(value.toString().toLowerCase()==data[r][c].toString().toLowerCase()){
sheet.getRange(r+1,c+1).activate().setBackground('#ffff55');
return;
}
}
}
}
}
This code is able to search across multiple sheets, it is obviously based on your published code but uses a memory (scriptProperties) to keep the search value 'alive' when changing from one sheet to the next one and to know when to search for it.
It has 2 non-optimal aspects : 1° you have to keep searching up to the last occurrence before you can begin a new search.
2° : when it switches from sheet n to sheet n+1 it first selects cell A1 before finding the value occurrence.
I guess it should be possible to get rid of these issues but right now I don't find how :-)
Maybe the approach is simply not the best, I started from a simple one sheet script modified and complexified... that's usually not the best development strategy (I know), but anyway, it was a funny experiment and a good logic exercise ...
Thanks for that.
function SearchAndFind() {
//determine value of selected cell
var sh = SpreadsheetApp.getActiveSpreadsheet();
var ss = sh.getActiveSheet();
var cell = ss.getActiveCell();
var value = cell.getValue();
if(ScriptProperties.getProperty('valueToFind')!=''){value = ScriptProperties.getProperty('valueToFind')};
//create array with sheets in active spreadsheet
var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets()
var sheetNumber = sheets.length;
var currentSheet = ss.getIndex()-1;
Logger.log(currentSheet);
//loop through sheets to look for value
for (var i = currentSheet ; i<sheetNumber ; ++i ){
Logger.log('currentSheet = '+i)
//Set active cell to A1 on each sheet to start looking from there
SpreadsheetApp.setActiveSheet(sheets[i])
// sheets[i].getRange(1,1).activate();
//set variables to loop through data on each sheet
var activeR = cell.getRow()-1;
var activeC = cell.getColumn()-1;
var data = sheets[i].getDataRange().getValues()
var step = 0;
//loop through data on sheet
for(var r=activeR;r<data.length;++r){
for(var c=activeC;c<data[0].length;++c){
step++
Logger.log('sheet : '+i+' step:'+step+' value '+value+' = '+data[r][c]);
if(data[r][c]==''||(step==1&&i==currentSheet)){ continue };
if(value.toString().toLowerCase()==data[r][c].toString().toLowerCase()){
sheets[i].getRange(r+1,c+1).activate().setBackground('#ffff55');
ScriptProperties.setProperty('valueToFind',value);
return;
}
}
}
cell = sheets[i].getRange(1,1);
}
ScriptProperties.setProperty('valueToFind','');
Logger.log('reset');
}

How to make Google form submission sort into separate sheets?

I can only get this to sort automatically when I input the text manually into the cell. I've tried changing to OnFormSubmit but no luck. How can I rewrite this to have Google Docs automatically sort the form-submitted answers to separate tabs?
function onEdit(event) {
// assumes source data in sheet named Needed
// target sheet of move to named Acquired
// test column with yes/no is col 4 or D
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = SpreadsheetApp.getActiveSheet();
var r = SpreadsheetApp.getActiveRange();
if(s.getName() == "Inbox" && r.getColumn() == 6 && r.getValue() == "Los Angeles") {
var row = r.getRow();
var numColumns = s.getLastColumn();
var targetSheet = ss.getSheetByName("Los Angeles");
var target = targetSheet.getRange(targetSheet.getLastRow() + 1, 1);
s.getRange(row, 1, 1, numColumns).moveTo(target);
s.deleteRow(row)
}
}
Dont write the sorted sheet data manually. Instead use a single QUERY formula per sheet. With it you can filter sort grouo and pivot your data as you like.

Find value in spreadsheet using google script

Situation:
1 spreadsheet
multiple sheets
1 cell selected (may vary)
What I'd like to do is to find and set focus to the next cell in any sheet that matches the selected cell (case insensitive) upon clicking a button-like image in the spreadsheet. Sort of like a custom index MS Word can create for you.
My approach is:
- set value of the selected cell as the variable (succeeded)
- find the first cell that matches that variable (not the selected cell) (no success)
- set value of found cell as variable2 (no success)
- set the focus of spreadsheet to variable2 (no success)
function FindSetFocus()
{
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var activecell = sheet.getActiveCell();
var valueactivecell = activecell.getValue();
//here comes the code :)
}
I have found this snippet in the following topic, but I'm having a little trouble setting the input and doing something with the output: How do I search Google Spreadsheets?
I think I can replace 'value' with 'valueactivecell', but I don't know how to set the range to search through all sheets in the spreadsheet. Also, I'd like the output to be something I can set focus to using something like 'ss.setActiveSheet(sheet).setActiveSelection("D5");'
/**
* Finds a value within a given range.
* #param value The value to find.
* #param range The range to search in.
* #return A range pointing to the first cell containing the value,
* or null if not found.
*/
function find(value, range) {
var data = range.getValues();
for (var i = 0; i < data.length; i++) {
for (var j = 0; j < data[i].length; j++) {
if (data[i][j] == value) {
return range.getCell(i + 1, j + 1);
}
}
}
return null;
}
also found this but no luck on getting it to work on the selected cell and setting focus: How do I search for and find the coordinates of a row in Google Spreadsheets best answer, first code.
Please bear in mind that I'm not a pro coder :) If code samples are provided, please comment inline hehe.
Thanks in advance for any help.
Edit 24/10: Used the code from the answer below and edited it a bit. Now able to look through multiple sheets in a spreadsheet to find the value. The only problem with this bit is: My cell is highlighted yellow, but the cell with the value found isn't selected. See code below for hopping through sheets. I can't get my head around this :)
function SearchAndFind() {
//determine value of selected cell
var sh = SpreadsheetApp.getActiveSpreadsheet();
var ss = sh.getActiveSheet();
var cell = ss.getActiveCell();
var value = cell.getValue();
//create array with sheets in active spreadsheet
var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
//loop through sheets to look for value
for (var i in sheets) {
//Set active cell to A1 on each sheet to start looking from there
SpreadsheetApp.setActiveSheet(sheets[i])
var sheet = sh.getActiveSheet();
var range = sheet.getRange("A1");
sheet.setActiveRange(range);
//set variables to loop through data on each sheet
var activeR = cell.getRow()-1;
var activeC = cell.getColumn()-1;
var data = sheets[i].getDataRange().getValues()
var step = 0
//loop through data on the sheet
for(var r=activeR;r<data.length;++r){
for(var c=activeC;c<data[0].length;++c){
step++
Logger.log(step+' -- '+value+' = '+data[r][c]);
if(data[r][c]==''||step==1){ continue };
if(value.toString().toLowerCase()==data[r][c].toString().toLowerCase()){
sheet.getRange(r+1,c+1).activate().setBackground('#ffff55');
return;
}
}
}
}
}
Here is an example of such a function, I inserted a drawing in my spreadsheet representing a button which I assigned the script so it's easy to call.
I added a feature to set a light yellow background on the resulting selected cell so it's easier to see the selected cell but this is optional.
Code
function findAndSelect(){
var sh = SpreadsheetApp.getActiveSpreadsheet();
var ss = sh.getActiveSheet();
var cell = ss.getActiveCell();
cell.setBackground('#ffff55');// replace by cell.setBackground(null); to reset the color when "leaving" the cell
var activeR = cell.getRow()-1;
var activeC = cell.getColumn()-1;
var value = cell.getValue();
var data = ss.getDataRange().getValues();
var step = 0
for(var r=activeR;r<data.length;++r){
for(var c=activeC;c<data[0].length;++c){
step++
Logger.log(step+' -- '+value+' = '+data[r][c]);
if(data[r][c]==''||step==1){ continue };
if(value.toString().toLowerCase()==data[r][c].toString().toLowerCase()){
ss.getRange(r+1,c+1).activate().setBackground('#ffff55');
return;
}
}
}
}
Caveat
This code only searches 'downwards', i.e. any occurrence in a row that would precede the selected cell is ignored, same for columns...
If that's an issue for you then the code should be modified to start iterating from 0. But in this case if one need to ignore the initial starting cell then you should also memorize its coordinates and skip this value in iteration.

Resources