javascript - Excel office-js API - Insert values to a blank sheet -
how can insert values blank sheet?
way know of inserting values retrieving range , inserting values using values
property, such as
range.getrange("a1:" + cellbottomright); range.load("values"); context.sync().then(function () { range.values = twodimensionalarrayofvalues; });
is there simpler way using single function insert values, rather first retrieving range?
thanks!
edit:
i've been trying create new sheet , insert 2-dimensional array it, values inserted starting cell a1.
far, managed following:
let neesheet = context.workbook.worksheets.add("new sheet"); newsheet.activate(); newsheet.getrange("a1").values = twodimensionalarray; context.sync();
but didn't work.
how can work?
thanks!
(adding answer in response new information @avi12 added question above, under "edit")
philip's answer above correctly shows how insert single value cell a1 of worksheet. address specific scenario you've described in (updated) question, here code snippets (one in typescript , other in javascript) show how create new worksheet , add data worksheet, using 2-dimensional array of data. key thing point out here i'm retrieving range using getresizedrange (passing in dimensions of array), size of range matches size of data set i'm inserting it.
note: can , try these snippets using script lab (https://aka.ms/getscriptlab). install script lab add-in (free), choose "import" in navigation menu, , use following gist url: https://gist.github.com/kbrandl/01c4faf352c34286188311c1198f6307.
typescript:
async function run_ts() { try { await excel.run(async (context) => { // define values inserted new sheet let values = [["a1", "b1", "c1"], ["a2", "b2", "c2"]]; // create , activate new sheet let sheets = context.workbook.worksheets; let newsheet = sheets.add("new sheet ts"); newsheet.activate(); // add data new sheet let range = newsheet.getrange("a1").getresizedrange(values.length - 1, values[0].length - 1); range.values = values; // sync await context.sync(); console.log("finished run_ts function"); }); } catch (error) { officehelpers.ui.notify(error); officehelpers.utilities.log(error); } }
javascript:
function run_js() { excel.run(function (context) { // define values inserted new sheet var values = [["a1", "b1", "c1"], ["a2", "b2", "c2"]]; // create , activate new sheet var sheets = context.workbook.worksheets; var newsheet = sheets.add("new sheet js"); newsheet.activate(); // add data new sheet var range = newsheet.getrange("a1").getresizedrange(values.length - 1, values[0].length - 1); range.values = values; // sync return context.sync() .then(function () { console.log("finished run_js function"); }); }) .catch(function (error) { officehelpers.ui.notify(error); officehelpers.utilities.log(error); }); }
Comments
Post a Comment