Is it possible / is there a convenience function to copy a range of cells and/or a whole worksheet from one Excel sheet to another using ExcelJS?
copying worksheets with Merged cells
var ws1 = workbook.getWorksheet('demo');
let copySheet = workbook.addWorksheet('newdemo');
copySheet.model = Object.assign(ws1.model, {
mergeCells: ws1.model.merges
});
copySheet.name = 'new demo';
var sourceWorkbook= new Excel.Workbook();
var sourceWorksheet;
sourceWorkbook.xlsx.readFile("template.xlsx").then(function(){
sourceWorksheet= sourceWorkbook.getWorksheet(1);
var targetWorkbook = new Excel.Workbook;
var targetSheet = targetWorkbook.addWorksheet();
sourceWorksheet.eachRow((row, rowNumber) => {
var newRow = targetSheet.getRow(rowNumber);
row.eachCell((cell, colNumber) => {
var newCell = newRow.getCell(colNumber)
for(var prop in cell)
{
newCell[prop] = cell[prop];
}
})
})
This is what I done with my project. It works well.
You can copy the whole worksheet from one Excel sheet to another using ExcelJS. Below code will work
const Excel = require('exceljs');
async function copyExcel() {
let targetWorkbook = new Excel.Workbook();
targetWorkbook = await targetWorkbook.xlsx.readFile('target.xlsx');
const targetWorksheet = targetWorkbook.getWorksheet('target'); // you can add new sheet as well.
let sourceWorkbook = new Excel.Workbook();
sourceWorkbook = await sourceWorkbook.xlsx.readFile('source.xlsx');
const sourceWorksheet = sourceWorkbook.getWorksheet('source');
sourceWorksheet.eachRow({ includeEmpty: false }, (row, rowNumber) => {
var targetRow = targetWorksheet.getRow(rowNumber);
row.eachCell({ includeEmpty: false }, (cell, cellNumber) => {
targetRow.getCell(cellNumber).value = cell.value;
});
row.commit();
});
await targetWorkbook.xlsx.writeFile('target.xlsx');
}
copyExcel();
Related
I'm stuck trying to copy the values from my JSON scraping script to spreadsheet.
Does anyone know how to do that?
I'm stuck trying to know how to get the "longname" values to the memory and then using setValue once at the end.
I need to paste all the values here at the column B.
First I'm trying to resolve a single column, later I will need to paste a multi dimensional array to multiple columns. But that's only if I solve this.
Just a detail, on columnWithTickers I used only a range of 5 rows for testing purposes. Later I will use a dynamic value.
Code:
var ss = SpreadsheetApp.getActiveSpreadsheet();
var page1 = ss.getSheetByName("pag1");
let columnWithTickers = page1.getRange(2, 1, 5).getValues();
let targetColumn = page1.getRange(2, 2);
function printValuesFromJSON() {
if (!Array.isArray(columnWithTickers)) {
columnWithTickers = [[columnWithTickers]]
}
return columnWithTickers.map(tickers => {
try {
values = tickers[0].toString().split(",");
let url = `https://finance.yahoo.com/quote/${values}.SA/key-statistics?p=${values}.SA`;
let source = UrlFetchApp.fetch(url).getContentText()
let jsonString = source.match(/root.App.main = ([\s\S\w]+?);\n/)
if (!jsonString || jsonString.length == 1) return;
let data = JSON.parse(jsonString[1].trim());
let longname = data.context.dispatcher.stores.QuoteSummaryStore.price.longName.split();
/*let resultados = longname.map(vetor =>{
return ativosResultados = vetor[0].toString();
})*/
}
catch (error) {
return "N/A"
}
}
)
}
You can try the below function:
function attDiarios(){
var result = intervaloTickers.map(tickersAtuais =>
{
ativosFinais = tickersAtuais[0].toString().split(" ")
let url = `https://finance.yahoo.com/quote/${ativosFinais}.SA/key-statistics?p=${ativosFinais}.SA`;
let source = UrlFetchApp.fetch(url).getContentText()
let jsonString = source.match(/root.App.main = ([\s\S\w]+?);\n/)
if (!jsonString || jsonString.length == 1) return null;
let data = JSON.parse(jsonString[1].trim());
try{
var longNameValue = data.context.dispatcher.stores.QuoteSummaryStore.price.longName;
}
catch(err){
var longNameValue = 'N/A';
}
return [[longNameValue]]
}
)
sImport.getRange(5, 2, result.length, result[0].length).setValues(result);
}
I'm trying to display some data from google - the script below works for pulling the data - but I want to add a delay to it running so there's time for it to process the data when a change is made.
I've tried adding setTimeout() to the whole piece of code, but when I add it it turns back blank.
Any ideas?
https://codepen.io/jameswill77/pen/PoREWmK
const sheetId = '1Fa0SgniGrmW_0DCQriR6-XYj2eiRayTK_9HZG9BQYok';
const base = `https://docs.google.com/spreadsheets/d/${sheetId}/gviz/tq?`;
const sheetName = 'sheet 1';
const query = encodeURIComponent('Select *')
const url = `${base}&sheet=${sheetName}&tq=${query}`
const data = []
document.addEventListener('DOMContentLoaded', init)
const output = document.querySelector('.output')
function init() {
fetch(url)
.then(res => res.text())
.then(rep => {
//Remove additional text and extract only JSON:
const jsonData = JSON.parse(rep.substring(47).slice(0, -2));
console.log(rep)
const colz = [];
const tr = document.createElement('tr');
//Extract column labels
jsonData.table.cols.forEach((heading) => {
if (heading.label) {
let column = heading.label;
colz.push(column);
const th = document.createElement('th');
th.innerText = column;
tr.appendChild(th);
}
})
output.appendChild(tr);
//extract row data:
jsonData.table.rows.forEach((rowData) => {
const row = {};
colz.forEach((ele, ind) => {
row[ele] = (rowData.c[ind] != null) ? rowData.c[ind].v : '';
})
data.push(row);
})
processRows(data);
})
}
function processRows(json) {
json.forEach((row) => {
const tr = document.createElement('tr');
const keys = Object.keys(row);
keys.forEach((key) => {
const td = document.createElement('td');
td.textContent = row[key];
tr.appendChild(td);
})
output.appendChild(tr);
})
}
<div class="output"></div>
document.addEventListener('DOMContentLoaded', () => {
setTimeout(init, 3000);
});
Is this behaviour what you are looking for?
I need to read only visible rows from an excel file.
Now I am getting with all rows in excel file while using the following code.
let fileReader = new FileReader();
fileReader.readAsBinaryString(selectedFile);
fileReader.onload = (event) => {
let data = event.target.result;
let workbook = XLSX.read(data, { type: "binary" });
let rowObject = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[workbook.SheetNames[j]]);
import * as Excel from "exceljs/dist/exceljs.min.js";
checkHiddenRowAndColumns(file) {
const workbook = new Excel.Workbook();
const arryBuffer = new Response(file).arrayBuffer();
arryBuffer.then(function (data) {
workbook.xlsx.load(data)
.then(function () {
const worksheet = workbook.getWorksheet(1);
//check hidden columns
for(var i=0; i < worksheet.columns.length; i++) {
if(worksheet.columns[i].hidden == true){
console.log('hidden columns' + i)
}
}
//check hidden rows
worksheet.eachRow(function (row,rowNumber) {
if(row.hidden == true) {
console.log('hidden row' + rowNumber)
}
});
this.spinnerService.hide();
});
});
}
onFileChange(evt: any) {
this.spinnerService.show();
this.data = [];
this.uploadedFileName = '';
/* wire up file reader */
const target: DataTransfer = <DataTransfer>(evt.target);
if (target.files.length > 1) throw new Error('Cannot use multiple files');
if (target.files.length === 1) {
this.checkHiddenRowAndColumns(target.files[0]);
this.enableImportExcel = true;
const file = target.files[0];
this.searchFilterForm.get('edt').setValue(file);
this.uploadedFileName = target.files[0].name;
if (target.files.length == 1 && (target.files[0].type == ".xlsx" || target.files[0].type == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" || target.files[0].type == "application/vnd.ms-excel")) {
const reader: FileReader = new FileReader();
reader.onload = (e: any) => {
/* read workbook */
const bstr: string = e.target.result;
const wb: XLSX.WorkBook = XLSX.read(bstr, { type: 'binary' });
/* grab first sheet */
const wsname: string = wb.SheetNames[0];
const ws: XLSX.WorkSheet = wb.Sheets[wsname];
this.data = (XLSX.utils.sheet_to_json(ws, { header: 1, raw: false }));
};
reader.readAsBinaryString(target.files[0]);
}
else {
this.enableImportExcel = false;
}
} else {
this.uploadedFileName = "";
}
}
There is skip hidden row option in sheet_to_csv method I just used it and reparse the output:
function xslxRemoveSheetHiddenRows(sheet){
let csv=XLSX.utils.sheet_to_csv(sheet,{skipHidden:true})
let filteredWorkbook=XLSX.read(csv, {type: 'binary'});
return filteredWorkbook.Sheets.Sheet1;
}
And usage example:
//loading cell's style is essential to detect hidden rows and columns
let workbook = XLSX.read(data, { type: 'binary', cellStyles: true });
//unhide the title rows to save it from elimination
workbook.Sheets.Data["!rows"][0].hidden = false;
//removing hidden rows and columns
let sheet = xslxRemoveSheetHiddenRows(workbook.Sheets.Data);
I have an Excel file with the following template.
Name, Surname, Class
Alex, Smith, B1,
Maria, Smith, B2
The Excel file has multiple sheets with data in different languages.
I want to read from the Excel file and to create a hash structure (key/value) because I want to add later more information in each entry.
I have achieved to set the keys names for each entry but I cannot understand how I can import the values for each entry.
You can see the required format of the structure here:
var arr = [{
"name":{default:"Alex", cellId:"B1"},
"surname":{default:"Smith", cellId:"B2"},
"class":{default: "B1", cellId:"B3"}
},
{
"name":{default:"Maria", cellId:"C1"},
"surname":{default:"Smith", cellId:"C2"},
"class":{default: "B1", cellId:"C3"}
} ]
$("#btn").on("change", function(e) {
e.preventDefault();
var files = e.target.files;
var i, f;
for (i = 0, f = files[i]; i != files.length; ++i) {
var reader = new FileReader();
reader.onload = function(e) {
var data = e.target.result;
var workbook = XLSX.read(data, {
type: "buffer",
blankRows: true,
defval: ' '
});
var sheet_name_list = workbook.SheetNames;
var theQuestionLanguage = sheet_name_list; //english
var theExcelDataArray = [];
var test;
var data = [];
var headers = {};
sheet_name_list.forEach(function(y) {
var worksheet = workbook.Sheets[y];
var headers = {};
var data = [];
for (z in worksheet) {
//parse out the column, row, and value
var col = z.substring(0, 1);
var row = parseInt(z.substring(1));
var value = worksheet[z].v;
//store header names
if (row == 1 && !headers[value]) {
headers[value] = {};
}
console.log(headers);
if ((headers[value]) && (row !== 1)) {
headers[value].default = "value"
console.log("headers");
}
}
//drop those first two rows which are empty
});
};
reader.readAsArrayBuffer(f);
}
});
First of all, Save As your Excel file in CSV format.
After that, go to this website : Let's go. In this website you can add for information in your each entry and convert them into key/value pair.
I hope this this above information will help you.
I am trying to parse and read every cell from an Excel sheet; it seems that I am parsing the file but I just can't go through each cell and display them.
I am using the following code:
var workbook = XLSX.read('datasets/persons.xlsx', { type: 'binary' });
var sheet_name_list = workbook.SheetNames;
// console.log(sheet_name_list);
sheet_name_list.forEach(function (y) { /* iterate through sheets */
//Convert the cell value to Json
console.log(y);
var roa = XLSX.utils.sheet_to_json(workbook.Sheets[y]);
console.log(roa);
if (roa.length > 0) {
result = roa;
}
});
I am getting an empty array when I try to print console.log(roa), any idea how I should iterate through each cell from the file?
you can use
XLSX.utils.sheet_to_row_object_array(workbook.Sheets[y])
to parse each cells in excel file.
Here is full code use to display Excel sheet file using JavaScript and JQuery.
function handleFile(e) {
//alert(e);
var exceljsonObj = [];
var files = e.target.files;
var i, f;
for (i = 0, f = files[i]; i != files.length; ++i) {
var reader = new FileReader();
var name = f.name;
reader.onload = function (e) {
var data = e.target.result;
var result;
var workbook = XLSX.read(data, { type: 'binary' });
var sheet_name_list = workbook.SheetNames;
sheet_name_list.forEach(function (y) { /* iterate through sheets */
//var exceljsonObj = [];
var rowObject = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[y]);
exceljsonObj = rowObject;
for(var i=0;i<exceljsonObj.length;i++){
//var recordcount = exceljsonObj.length;
var data = exceljsonObj[i];
$('#myTable tbody:last-child').append("<tr><td>"+data.ID+"</td><td>"+data.Name+"</td><td>"+data.Months+"</td></tr>");
}
//alert(exceljsonObj.length);
$('#alermessage').each(function() {
//this points to item
alert('Record Count is '+exceljsonObj.length);
});
});
};
reader.readAsArrayBuffer(f);
}
}
$(document).ready(function(){
$('#files').change(handleFile);
});