I'm just trying to figure out how to append a single row to an xlsx file. For example, append array = [1 2 3 4 5] to the first empty row using columns 1,2,3,4,5. Ideally I'd start with an empty .xlsx file, and repeatedly rerun this program, which appends a new row to the file each time it is ran.
I'm attempting to use exceljs, but any test writes I try to do to a file say corrupted when I attempt to open them.
edited code (still not working):
var Excel = require('exceljs');
var workbook = new Excel.Workbook();
var sheet = workbook.addWorksheet('rssi');
file = 'testfile.xlsx'
var array = [1,2,3,4,5]
sheet.addRow(array)
workbook.xlsx.writeFile(file)
.then(function() {
console.log('Array added and file saved.')
});
Output is zero bytes and cannot be opened by Microsoft Excel. Says, "The file format or file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file."
Basically, you was trying to add the row in method which was called after file write. Try this example:
var workbook = new Excel.Workbook();
file = 'testfile.xlsx'
var array = [1,2,3,4,5]
var sheet = workbook.addWorksheet('rssi');
sheet.addRow(array)
workbook.xlsx.writeFile(file)
.then(function() {
console.log('Array added and then file saved.')
});
But it add only one row at a time
var spread_sheet = require('spread_sheet');
var row = "1,2,Jack,Pirate";
var filePath = '/home/Pranjal/Desktop/test.xlsx';
var sheetName = "Sheet1";
spread_sheet.addRow(row,filePath,sheetName,function(err,result){
console.log(err,result)
})
Add row to spreadsheet:-
I also stuck with the same functionality issue, so I used 'spread_sheet' module.
It worked for me
Related
I have a JSON data like:
data = [
name: "test",
age:50,
country: "America"
]
And I read excel file which looks like that
https://imgur.com/a/InyUXxv
(File is more complex, I have more static images and a lot of more text --> around 1000 cells filled)
So The problem is that I need to fill the JSON data to the excel file.
The Excel file will allways be the same and the data will allways go to same cell.
I can read this Excel template file and update it and write it back in new file but if I do that, I lost images. New file is without images
With excel4node I can write separate images to excel file but I don't know how can i read that file and than write the same back..
Code example for xlsx npm package, where I lost images when writing same file to Excel..
Can someone help me with anything? I am stuck here for a few days and I can't find a solution..
Node.js code:
var xlsx = require("xlsx");
exports.generateExcel = async () => {
var excelFile = await
xlsx.readFile("./utilities/template.xlsx");
const { SheetNames: sheetNames } = excelFile;
var data = xlsx.utils.sheet_to_json(excelFile.Sheets[sheetNames[0]]);
console.log(data);
var ws = xlsx.utils.json_to_sheet(data);
var wb = xlsx.utils.book_new();
xlsx.utils.book_append_sheet(wb, excelFile, "Tests");
xlsx.writeFile(excelFile, "./utilities/novooo.xlsx");
};
So When I write file it is written without images. In the template.xlsx there are images (I read this file in the beginning of the code and store it as variable)
In a google sheet, I managed to filter file name and file type and list all the particular files needed from a google drive folder based on the conditions into a spreadsheet. I am having an issue to convert the excel files into spreadsheet because I'm opening the selected files using "SpreadsheetApp.openById(id)" in another function() to get the data range from the specific files.
Based on the requirement set, I was been asked to convert the excel files into spreadsheet before getting the range data and export those data into another sheet.
Below are the codes that i created to list the file name and file type, so i believe that the file conversion method might need to be implemented here as well because it involves the file filtering process and these are the files need to be converted later on. Please correct me if I am wrong.
function getChildFiles(parentName, parent, sheet) {
var fileIter = parent.searchFiles("title contains 'completed'and title contains 'Verification
Visit Direct Suppliers'and mimeType='application/vnd.openxmlformats-
officedocument.spreadsheetml.sheet'");
var output = [];
var now = new Date();
var date = new Date();
var copy = new Date(date);
while (fileIter.hasNext()) {
var file = fileIter.next();
var fileName = file.getName();
var fileType = file.getMimeType();
var filecreatedate = file.getDateCreated();
var fileUpdate = file.getLastUpdated()
var path = parentName + ' |--> ' + fileName;
var fileID = file.getId();
var Url = 'https://drive.google.com/open?id=' + fileID;
output.push([fileID, fileName, path, Url,filecreatedate,fileUpdate,copy]);
Logger.log(fileType);}
if (output.length) {
var last_row = sheet.getLastRow();
sheet.getRange(last_row + 1, 1, output.length, 7).setValues(output);
SpreadsheetApp.flush();}
var childFolders = parent.getFolders();
while (childFolders.hasNext()) {
var childFolder = childFolders.next();
var childFolderName = childFolder.getName();
getChildFiles( parentName + ' |--> ' + childFolderName, childFolder, sheet);}}
So I'm trying to implement the file conversion method from excel file to spreadsheet, so that i can extract data from the excel file after the file successfully converted to spreadsheet.
I need to overwrite with an Excel file a fixed Google spreadsheet that keep both file ID and sheet ID .
Here below the code written in Google Apps Script that works but everytime generate a new id for the sheet.
function overwrite() {
const xlsxFileName = "XXX.xlsx"; // Please set the filename of XLSX file.
const spreadsheetId = "1JnsV5Vpp0xXj1fNyDeKV04PReYGN4v2oBVcQb6bvBUA"; // Please set the Spreadsheet ID. This Spreadsheet is overwritten by EXCEL data.
const xlsx = DriveApp.getFilesByName(xlsxFileName || "XXX.xlsx");
if (!xlsx.hasNext()) throw new Error("No excel file.");
Drive.Files.update({mimeType: MimeType.GOOGLE_SHEETS}, spreadsheetId, xlsx.next().getBlob());
}
My need is to import the information included in a specific Excel sheet into a specific sheet in Google Sheet. My goal is to be able to keep the spreadsheetID and sheetID in order to be able to link a dashboard in Google Data Studio with automatic update.
Basically you want a spreadsheet which sync with excel file and whenever the data update in Excel file, spreadsheet will update without change it's sheet id and use that spreadsheet to create a report on Looker (formerly Google Data Studio).
What exactly logic use
Create two spreadsheets :
[An excel file convert to the google spreadsheet with updation gid everytime when excel file updates ] (use Apps Script)
[Import data from converted file to new or second google spreadsheet] (use Apps Script).
When you import data to new spreadsheet, the sheet id will never change and you can also use it on Looker.
var dstFileId = 'File_id'; // file Id of Existing Spreadsheet
function convertExceltoGoogleSpreadsheet(fileName) {
fileName = fileName || "excelfile.xlsx"; // excel_file_name.xlsx = name of specific Excel file
var excelFile = DriveApp.getFilesByName(fileName).next();
var fileId = excelFile.getId();
var srcFileId = fileId; // file Id of Excel file
Drive.Files.update({}, dstFileId, DriveApp.getFileById(srcFileId))
};
Upper code for 1st spreadsheet (for convert excel file to google spreadsheet)
****** must add Drive API service ******
var sourceSpreadsheetID = "id_of_1st_spreadsheet";
var sourceWorksheetName = "name_of_worksheet_of_1st_spreadsheet";
var targetSpreadsheetID = "id_of_2nd_spreadsheet";
var targetWorksheetName = "name_of_worksheet_of_2nd_spreadsheet";
function importData() {
var thisSpreadsheet = SpreadsheetApp.openById(sourceSpreadsheetID);
var thisWorksheet = thisSpreadsheet.getSheetByName(sourceWorksheetName);
var thisData = thisWorksheet.getDataRange();
var toSpreadsheet = SpreadsheetApp.openById(targetSpreadsheetID);
var toWorksheet = toSpreadsheet.getSheetByName(targetWorksheetName);
var toRange = toWorksheet.getRange(1, 1, thisData.getNumRows(),
thisData.getNumColumns())
toRange.setValues(thisData.getValues());
}
this code for second spreadsheet (import data from 1st spreadsheet without change the sheet id)
Now you can use this new spreadsheet for create your report on Looker
Is there any way to modify existing excel file in node.js?
I've looked into exceljs but it does not provide any functionality that will just modify the existing data. It seems like it will write to a new stream.
Or did I miss something on exceljs?
Thanks in advance.
exceljs does let you modify Excel spreadsheets.
Here's an example of reading in an existing spreadsheet and writing it back out to a different file:
var Excel = require('exceljs');
var workbook = new Excel.Workbook();
workbook.xlsx.readFile('old.xlsx')
.then(function() {
var worksheet = workbook.getWorksheet(1);
var row = worksheet.getRow(5);
row.getCell(1).value = 5; // A5's value set to 5
row.commit();
return workbook.xlsx.writeFile('new.xlsx');
})
If you're using the Streams API with exceljs, you can also pipe your stream into fs.createWriteStream to write to a file as well.
Thankyou all answer.
same file you can update row value by below code No need to rename or create new file.
var Excel = require('exceljs');
let filename = 'src/write.xlsx';
let workbook = new Excel.Workbook();
await workbook.xlsx.readFile(filename);
let worksheet = workbook.getWorksheet("Sheet1");
// header id name dob
let row = worksheet.getRow(3);
console.log(row);
row.getCell(1).value = 2;
row.getCell(2).value = 'test';
row.getCell(3).value = '12/09/1991';
row.commit();
workbook.xlsx.writeFile('src/write.xlsx');
You can modify excel, below is the example.
var Excel = require('exceljs');
async function excelOp() {
let workbook = new Excel.Workbook();
workbook = await workbook.xlsx.readFile('question_39869739.xlsx'); // replace question_39869739.xls with your file
let worksheet = workbook.getWorksheet('sheetname'); // replace sheetname with actual sheet name
worksheet.getRow('rowNumber').getCell('cellNumber').value = 350; // replace rowNumber and cellNumber with the row and cell you want to modify
workbook.xlsx.writeFile('question_50508131.xlsx');
}
excelOp();
Have a look at https://www.npmjs.com/package/exceljs#interface for all the possible operations with exceljs.
i am currently working on a form which will take user input and add it to one row of an excel sheet, as of now i have managed to make excel sheet using 3rd party plugins(node-xls to be specific).
issue arises if i wanna add another row to the excel , it deletes the old entry and adds the new instead of appending the data to the next row.
tried reading the excel and then concatenating the buffers and writing the file again, but turns out it is corrupting the file and is rendering it unusable.
How do i append data to the end of the excel sheet? i am new to nodejs and buffers
var fs = require('fs');
var NodeXls = require('node-xls');
var tool = new NodeXls();
var xls = tool.json2xls({firstName: "arjun", lastName: "u", dob:"12/3/2008"}, {order:["firstName", "lastName", "dob"]});
fs.appendFile('output.xlsx', xls, 'binary', function(err){
if(err)
alert("File is readOnly or is being used by another application, please close it and continue!");
});
Have you tried Exceljs. It helps in Read, manipulate and write spreadsheet data and styles to XLSX and JSON.
check on the below link for details
https://www.npmjs.com/package/exceljs
Your problem of adding rows or append rows is solved here:
worksheet.addRow({id: 1, name: 'John Doe', dob: new Date(1970,1,1)});
var rowValues = [];
rowValues[1] = 4;
rowValues[5] = 'Kyle';
rowValues[9] = new Date();
worksheet.addRow(rowValues);
// Add an array of rows
var rows = [
[5,'Bob',new Date()], // row by array
{id:6, name: 'Barbara', dob: new Date()}
];
worksheet.addRows(rows);
Install npm module 'spread_sheet', it will definitely resolve the issues of adding row as well as reading rows from spreadsheet from any sheet.
It will add one row at a time
var spread_sheet = require('spread_sheet');
var row = "1,2,Jack,Pirate";
var filePath = '/home/Pranjal/Desktop/test.xlsx';
var sheetName = "Sheet1";
spread_sheet.addRow(row,filePath,sheetName,function(err,result){
console.log(err,result)
})