How to make excel cells readonly using Javascript? - javascript

I have used ignite ui excel library to create an excel workbook using JavaScript. But unfortunately I didn't find any method to make columns/rows of excel read-only in their library. Is there a way we could make columns read-only before creating an excel sheet in JavaScript/Jquery?

I achieved this with the following code/steps:
By first making the entire excel sheet protected by using the code:
sheet.protect();
{sheet is my worksheet name}
Then by unlocking certain cells of excel sheet using the code:
sheet.getCell('H'+j).cellFormat().locked(false);
{where H is the column name and j is a row number, an integer value}
Hope that helps someone else.

overview:
Im using nodejs and exceljs and I was searching for save new row data on my xlsx file while the file is open for read the info (no to save) on windows 10, but due to excel lock the file i was not able to write to the file, exceljs threw me an exception ( Error : EBUSY: resource busy or locked). i was searching for the property "ReadOnlyRecommended" on exceljs for save the file with ReadOnlyRecommended = true, this way i can read the file and at the same time write on it (in the original file, because it is read only), but unfortunately exceljs doesnt have such option. So after a long search I achieved this using fs.chmod from
const fs = require('fs'); when i create for the first time or edit i use fs.chmodSync(excelFilePath, 0o600); for be able to write on the file but when i finish to write i use fs.chmodSync(excelFilePath, 0o400); to set the file on read only, this way when an user open the excel file this is in read only mode so excel will not lock the file.
i hope this help somebody.
https://www.geeksforgeeks.org/node-js-fs-chmod-method/

Excel.run(function (ctx) {
//Worksheet
var sheet = ctx.workbook.worksheets.getItem("Sheet1");
//Entire Range
var entireRange = sheet.getRange();
entireRange.format.protection.locked = false;
//Specific Range
var range = sheet.getRange("A1:B5");
return ctx.sync()
.then(() => {
//Set specific range "locked" status to true.
range.format.protection.locked = true;
})
.then(ctx.sync)
.then(() => {
//Protect Entire sheet
sheet.protection.protect({
allowInsertRows: false,
allowDeleteRows: false
});
});
}).catch(errorHandler);

Related

Reference error: "Workbook" is not defined

I wanna use the next java script code:
function dumpVal(file) {
if (file !=null) {
var wb = new Workbook.create(file);
var sheet = wb.getSheet("Tabelle1");
for (myrow = 1; !isCellEmpty(sheet, myrow, 0); myrow++) {
dataset.setColumnValue("A",getNumericValue(sheet,myrow,0));
dataset.storeResultRow();
}
}
return;
}
but when I am compiling it I receive the next error message: ReferenceError: "Workbook" is not defined.
Can someone to tell me what am I doing wrong?
You recieve the error with the followig line of code:
var wb = new Workbook;
At the point where you create the workbook (new Workbook) you refer to a class called "Workbook". At this point your script dont have a class called Workbook it.
Solution:
You should check your scripts if the class is included and its naming.
Maybe the class is initialized later!
For debug purposes you can try to create the class a line before:
class Workbook{ }
If you recieve an error now because Workbook needs a method called "create", you know that the class is just missing.
I assume that you want to parse excel file from your web application, the library that you are using is for developing add-ins for excel not web application :
Excel JavaScript API programming overview
This article describes how to use the Excel JavaScript API to build add-ins for Excel 2016. It introduces key concepts that are fundamental to using the APIs, such as RequestContext, JavaScript proxy objects, sync(), Excel.run(), and load(). The code examples at the end of the article show you how to apply the concepts.
source :
https://dev.office.com/docs/add-ins/excel/excel-add-ins-javascript-programming-overview
If you want to parse Excel in your web application I suggest to use this library :
https://github.com/SheetJS/js-xlsx
I did not use it so I cant garanty it, but you can look for similar librarys.

Read data from excel to database in sailsjs

Recently, I try to learn sails.js. Thus I learn it through google and internet, and sails.js is still new, I encountered some trouble while finding any example of reading data from excel (*.xls and *.xlsx files). Can anyone show me how? On google, I found xlsx module (install by npm install xlsx ) but I still dont know what I have to write in controller and in view files. Thank you a lot!
xlsx will permit you to read a file at the server level, but you're going to have to work on the code to get that data into your views. I can't tell if you're trying to upload files and then read them or just read a static file. At any rate I hope that this is a start as it surely isn't a comprehensive solution.
Here is some example code from one of my scripts that goes down the rows and gets some info from some cells.
var XLSX = require('xlsx'),
xls_utils = XLSX.utils;
var workbook = XLSX.readFile('./file.xls');
var num_rows = xls_utils.decode_range(sheet['!ref']).e.r;
var sheet = workbook.Sheets[workbook.SheetNames[0]];
for(var i = 0, l = num_rows; i < l; i++){
// Get cell in {c}olumn 2 (0=1 like arrays) and {r}ow: i
var cell = xls_utils.encode_cell({c:1, r:i});
var value = sheet[cell];
// Do something with value here
}
You can do a lot more with it and you'll have to play around with it. I find the documentation to be a little rough to get through but the info is all there.

Exporting an array to excel file with cell formatting

I'm currently trying to export an array to an excel file with cell formatting.
I'm starting off with this code here:
https://github.com/SheetJS/js-xlsx/blob/master/tests/write.js
But the problem is that whenever I'm trying to export it (save the file as an xlsx file) this is the error that shows up in the console:
Uncaught TypeError: Cannot read property 'writeFileSync' of undefined xlsx.js:5182
writeSync xlsx.js:5182
writeFileSync xlsx.js:5173
process_xlsx Test.html:379
reader.onload Test.html:438
The last 2 lines are basically the part of the code which says
XLSX.writeFile(wb, 'sheetjs.xlsx');
I know wb is not undefined as if I try and do console.log of it, the excel spreadsheet shows up properly :|
Can someone help me with this? I'm also trying to have each cell have a different formatting (IE different color/bolded/filled/etc)
You base your code on a node.js test. The documentation states:
Writing Workbooks
For writing, the first step is to generate output data. The helper
functions write and writeFile will produce the data in various formats
suitable for dissemination. The second step is to actual share the
data with the end point. Assuming workbook is a workbook object:
nodejs write to file:
/* output format determined by filename */
XLSX.writeFile(workbook, 'out.xlsx');
/* at this point, out.xlsx is a file that you can distribute */
write to binary string (using FileSaver.js):
/* bookType can be 'xlsx' or 'xlsm' or 'xlsb' */
var wopts = { bookType:'xlsx', bookSST:false, type:'binary' };
var wbout = XLSX.write(workbook,wopts);
function s2ab(s) {
var buf = new ArrayBuffer(s.length);
var view = new Uint8Array(buf);
for (var i=0; i!=s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
return buf;
}
/* the saveAs call downloads a file on the local machine */
saveAs(new Blob([s2ab(wbout)],{type:""}), "test.xlsx")
So to sum up: You try to use node.js internal functions in the browser, which fails. If you try to follow the seconds approach ( XLSX.write() instead of XLSX.writeFile()), you should be fine.

Edit xlsx file without lost format and formulas with XLSX.js

I need to edit a XLSX file in a nodejs application for create an order sheet. the file I need to edit have a specific format and some formulas. I try to use several libraries but the only one I found that able to read and write xlsx files is XLSX.js.
But when I try to read the xlsx file and write the same content in a file, I lost the format and all formulas on the new file. Please find hereunder the piece of code that I use :
var xl = require('../public/javascripts/xlsx'),
fs = require('fs-extra'),
inFile = 'conf/X-Pole_Order_Form.xlsx',
outFile = "conf/tmp.xlsx";
fs.copy(inFile, outFile, function (err) {
if (err) {
throw new Error('Not enable to copy excel file');
}
fs.readFile(outFile, 'base64', function (err, content) {
if (err) {
throw new Error('Problem by reading excel file');
}
var sheet = xl(content);
fs.writeFile(outFile, sheet.base64, 'base64');
});
});
Do you have any idea or other solution to propose ?
Thanks for your help.
According to this two year old blog post by the author of that library (emphasis mine):
Right now XLSX.js supports reading data from multiple worksheets, the
names of the worksheets, the active worksheet, and file metadata. It
does not support the reading of formatting information, macros,
charts, or anything else.
Reading through the changelog for that file I don't see much was added that is format related. There is a pull request from someone that adds a little bit of formatting that you could try to implement but I don't think you're going to get full-blown Excel formatting from this library anytime soon.

Changing Excel data with JavaScript

I am working on a tool where I control a Excel sheet using JavaScript.
Here is a requirement that, I need to change the Excel cell data.
I was doing something like this:
1. Open Excel as:
excel = new ActiveXObject("Excel.Application");
excel.Visible = false;
excel.DisplayAlerts = false;
workBook = excel.WorkBooks.open("c:\\excel.xls");
workSheet = workBook.Worksheets("Work_sheet_1");
2. Make change as:
WorkSheet.Cells(10,20).value = "10";
console.log("Value stored in excel is: "+WorkSheet.Cells(10,20).value);
3. Close as:
excelWorkbook.save();
excelWorkbook.Close(true, "c:\\excel.xls").
workBook.Close(false);
excel.application.quit();
excel = null;
I run it in browser, and I get log as:
Value stored in excel is: 10
Now whenever I make any change in Excel through JavaScript, I can always see the correct log report, But in excel, this changes are either saved at a delayed of 2 - 3 min, or never saves any change. this seems a kind of weird. Over that, when try to open the excel sheet manually from folder, it gives Edit-mode Lock Pop-up.
Can anyone tell me where am I heading wrong?

Categories

Resources