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)
})
Related
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
I have an excel sheet with lots of spaces in between the content in each cell. I would like to keep that cell unaffected, so I would like to create a copy of the same and remove all the spaces of cell content. Is it possible to do from a nodejs code?
You could do so using xlsx package from npm.
copy the File via node
const fs = require('fs');
fs.copyFile('source.xlsx', 'newFile.xlsx', (err) => {
if (err) throw err;
});
read the File to any Format you like with xlsx (code simplified):
XLSX = require('xlsx');
workbook = XLSX.read('newFile.xlsx', {type: 'binary'});
let worksheet = workbook.Sheets[workbook.SheetNames[0]];
initialData = XLSX.utils.sheet_to_json(worksheet);
console.log('initialData ')
now you have the first worksheet of your copied file as JSON and can perform whatever changes you like.
After using eg trim on every object you can write that JSON back to an Excel File
let workbook1 = XLSX.utils.book_new();
let worksheet1 = XLSX.utils.json_to_sheet();
XLSX.utils.book_append_sheet(workbook1, worksheet1, 'WorksheetName');
XLSX.writeFile(workbook1, 'newFile.xlsx');
The first step is optional as you are only working inside the JSON copy an writing a new file afterwards, but I mentioned it as it was in the original question.
If you meant to remove the leading and the trailing white spaces, then this function should trim the white spaces from the header and all cells.
Please test it thoroughly before using it for production:
function trim_cells(ws) {
var range = XLSX.utils.decode_range(ws["!ref"]);
for (var R = range.s.r; R <= range.e.r; ++R) {
for (var C = range.s.c; C <= range.e.c; ++C) {
var coord = XLSX.utils.encode_cell({ r: R, c: C }),
cell = ws[coord];
if (!cell || !cell.v) continue;
// clean up raw value of string cells
if (cell.t == "s") cell.v = cell.v.trim();
// clean up formatted text
if (cell.w) cell.w = cell.w.trim();
}
}
}
Note - The above solution is found in the GitHub issue.
For more information on how to pass an excel worksheet (passed as a parameter) to the above function please look at the official GitHub link.
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
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.