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.
Related
I am reading an excel file using ExcelJs. However, when I got formula cells, It is not giving me value but giving formula.
Can any body help please.
var Excel = require('exceljs');
let workbook = new Excel.Workbook();
var FormulaParser = require('hot-formula-parser').Parser;
var parser = new FormulaParser();
workbook.xlsx.readFile('test.xlsx').then(function() {
var worksheet = workbook.getWorksheet(2);
var row = worksheet.getRow(1);
console.log(row.getCell(1).value); //5
console.log(row.getCell(2).value); //8
console.log(row.getCell(3).value); // =IFERROR(MIN(MAX($A1-$B1,0),$E1),"")
console.log(row.getCell(3).text); // blank
//I also tried with using FormulaParser library as below but getting null.
console.log(parser.parse(row.getCell(3).formula).result); // null
});
The result is here:
console.log(row.getCell(3).result);
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
My following 3 line code is used to create one file with sheet1(Year 2019) now would like to execute another page and need to store the result of it in same file as sheet2(Year 2020).
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet("Year 2019");
FileOutputStream fos = new FileOutputStream("C:\\Users\\dp\\Desktop\\MData1_Test_1.xlsx");
Row header_1 = sheet.createRow(rowNum[0]);
rowNum[0] = (rowNum[0] + 1);
header_1.createCell(0).setCellValue("Analytics");
Any help will be appreciated.
You can do something like this:
// open your first file
try (InputStream inp = new FileInputStream(fut.get())) {
Workbook wb = WorkbookFactory.create(inp);
// get sheet by name
Sheet sheet = wb.getSheet("Year 2019");
if (null != sheet) {
// if sheet exists => delete it
int index = wb.getSheetIndex(String name);
wb.removeSheetAt(index);
}
// create new sheet
sheet = wb.createSheet("Year 2019");
// proceed adding data
// row = sheet.createRow(0);
// row.createCell(0).setCellValue("data");
// ...
}
You can repeat these steps as many time as you need to manage as many sheets as you want.
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