Coder Social home page Coder Social logo

dtjohnson / xlsx-populate Goto Github PK

View Code? Open in Web Editor NEW
925.0 925.0 179.0 28.86 MB

Excel XLSX parser/generator written in JavaScript with Node.js and browser support, jQuery/d3-style method chaining, encryption, and a focus on keeping existing workbook features and styles in tact.

License: MIT License

JavaScript 99.71% C# 0.29%
excel javascript xlsx

xlsx-populate's People

Contributors

aaneitchik avatar alandoyle95 avatar buffaybu avatar djohnson-modernatx avatar dresende avatar dtjohnson avatar eddiecorrigall avatar excaliburzero avatar fauny avatar kuzalekon avatar lap123 avatar lesterlyu avatar mvelluet avatar nitsanavni avatar papb avatar quantumsheep avatar shohei-ihaya avatar smoke avatar thunder7553 avatar waterfoul avatar zypa13510 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

xlsx-populate's Issues

Support for deleting sheets

It would be great to be able to delete unused sheets. I'm loading Workbook with N sheets as a template. But then I need to remove some of them

getNamedCell not working

Hi,

I have been trying to use the getNamedCell function, but it does not work.

I tried to console.log the cell with the code:
var cell = workbook.getSheet(3).getNamedCell("Foo");
console.log(" ---------- named cell =============", cell);

But the terminal throws an error and states getNamedCell is not a function. Do you know what I'm doing wrong?

Thanks,
Khanhnhat

Date values are inconsistent

test.xlsx

This sheet has two cells of the same date 2017/04/04 20:00:00 GMT+0800.

But after parsed (in browser):

sheet.cell('A1').value() // 42829.8333333333
sheet.cell('B1').value() // 42829.833333333336
XlsxPopulate.numberToDate(42829.8333333333) // 2017/04/04 19:59:59
XlsxPopulate.numberToDate(42829.833333333336) // 2017/04/04 20:00:00

Sorry I can't reproduce Cell A1. It was input by a user and I just pasted it there.

Can we reduce the time of writing

Hi,

I am Amarnadh .

I like this module very much .

Now i am trying to write database records to xl sheet .

I have to write 600 rows in xlsx file and each row contains nearly 33 columns .

So total cells i have to write is 19800 for one sheet which is taking more than 30 seconds .

I have to write more than one sheet some times i have to write nealry 5 sheets like this .
So it will take 150 seconds .

Is there any optimised way to use to this plugin.

Because ,I have to write the sheet and have to send it as an attachment in the response in a request

Images always resized along with columns

Greetings and Happy Friday! This time I have a real bug for you, hopefully you can help me out once more. Using the provided example file and code snippet you should be able to see the problem I'm having.

If the source spreadsheet contains an image, and then the widths of the columns it overlaps are manipulated, the image will be scaled as well. However, there are options within Excel that allow users to explicitly determine the behavior of image resizing with respect to column manipulation (right-click image -> "Size and Properties" -> "Properties" section). In this case, I have set the image properties to "Don't move or size with cells", so I'm hoping that there is a way for that setting to be taken into account.

Hopefully this is enough to get started. Please let me know if I can be of any more help.

Thanks!

example-with-image.xlsx

const xlsxPopulate = require('xlsx-populate');

xlsxPopulate.fromFileAsync('./example-with-image.xlsx')
            .then(workbook => {
                const sheet = [
                    [1, 2, 3],
                    [4, 5, 6],
                    [7, 8, 9]
                ];

                const worksheet = workbook.sheet(0);

                // Insert sheet data
                const rowsCount = (sheet.length - 1);
                const columnCount = (sheet[0].length - 1);
                const cellStartInsert = workbook.find("${data}")[0];
                const cellEndInsert = cellStartInsert.relativeCell(rowsCount, columnCount);
                const addrStartCell = cellStartInsert.address();
                const addrEndCell = cellEndInsert.address();
                const rangeForSheet = worksheet.range(`${addrStartCell}:${addrEndCell}`);
                rangeForSheet.value(sheet);
                
                // Auto-size column widths and set heights to rows
                const addrHeaderEnd = cellStartInsert.relativeCell(0, columnCount).address();
                const rangeHeader = worksheet.range(`${addrStartCell}:${addrHeaderEnd}`);
                rangeHeader.forEach((cell, ri, ci, range) => {
                    const cellColumnLast = cell.relativeCell(rowsCount, 0);
                    const addrColumnFirst = cell.address();
                    const addrColumnLast = cellColumnLast.address();

                    const columnWidth = 25;

                    const addrColumn = cell.column().address().split(':')[0];
                    worksheet.column(addrColumn).width(columnWidth);
                });

                workbook.toFileAsync('./out.xlsx');
            });

Applying a lot of styles causes spreadsheet to need repair

When applying a ton of styles to a large amount of cells in a workbook, I then get the message "Excel could not open filename because some content is unreadable. Do you want to open and repair this workbook?"

As an example, I am using this code:

lineItemSheet.range(1, 2, lineItemRowOffset + 1, 2).style('numberFormat', 'mm/dd/yy');
lineItemSheet.range(1, 3, lineItemRowOffset + 1, 3).style('numberFormat', 'h:mm AM/PM');
lineItemSheet.range(1, 13, lineItemRowOffset + 1, 21).style('numberFormat', '$#,##0.00');

lineItemRowOffset in this case is around 15,000 so styles are being applied to tens of thousands of cells.

Is there a better way to apply styles or is this a bug?

Resulting workbook has more columns than original

First, this is an amazing project. It's been a pleasure to implement it. Also love the amount and quality of your documentation.

I'm curious if there is a way to control the dimensions of the generated spreadsheet to prevent too many empty columns from being returned.

The project I'm working on uses a template file that I use to dynamically populate. That file only shows columns to the width of the screen it's on, like "AC". The file that is returned has columns all the way up to "XFC". They are all empty so it would be nice if these could just not be returned.

Thanks!

Stuck whit value's

Hello,

im stuck at getting my values out of an template

i got an xlsx whit on A5 an ID and what to get the B5 C5 etc value's of that row and store them in an array ( im using nodejs)

var XlsxPopulate = require('xlsx-populate');
		csv.parseCSV("./csv/"+file, function(data){ //here i parse an csv and read the 1st data
		XlsxPopulate.fromFileAsync("./Klanten.xlsx") // here A5 got my ID<num>
			.then(workbook => {
				for (i = 0; i < data.length; i++) {
					//console.log(data[i].Account);
					var ddata = workbook.find("ID"+data[i].Account);
					console.log(ddata);
					//console.log(ddata[0]._ref.columnName); // whit 1.5.5 this works with 1.6.0 it fails
					//console.log(ddata[0]._ref.rowNumber);// whit 1.5.5 this works with 1.6.0 it fails
					//console.log(ddata[0]._ref.columnName +''+ ddata[0]._ref.rowNumber);
					const testdata = workbook.sheet(0).cell("A5").value();
					//var testdata = workbook.sheet(0).cell('A5').value();
					console.log(testdata);
				}
			});
		});

in 1.5.5 ddata =

[ Cell {
_row: Row { _sheet: [Object], _node: [Object], _cells: [Object] },
_node: { name: 'c', attributes: [Object], children: [Object] },
_ref:
{ type: 'cell',
columnAnchored: false,
columnName: 'A',
columnNumber: 1,
rowAnchored: false,
rowNumber: 5 } } ]

in 1.6.0 ddata =
[ Cell {
_row: Row { _sheet: [Object], _node: [Object], _cells: [Object] },
_columnNumber: 1,
_value: 'undefined' } ]

but in both sanario's (1.5.5 and 1.6.0)
testdata = undefined

am i doing someting wrong?

hope to hear from you

How could we open the downloaded excel in IE as well as Chrome?

Hello,

I am using blob to generate and download the excel file, but i want to open it as soon as its downloaded.

Its just because I want to auto close the pop up window from which user has downloaded the excel.

This will save two clicks(Open Excel & Close PopUp) per file and help to automate the process.

Thanks!
Suraj

row insertion

Is there a way to insert a row from a given row position?
Thank you.

Hyperlink support

Hi!
Thank you for this great library!
It's better than https://github.com/SheetJS/js-xlsx because it has styles and it easier to use. And it's pretty clear inside.
Are you planning to add Hyperlink support?
I can't find similar library which can add hyperlink to cell. It will be really useful.

row().value() not available

Hi,

It looks like that adding a value for a Row is not possible.

We can set a value for a cell;

sheet.cell("A1").value("something")

Or for a range:

sheet.range("A1:B1").value([ ["val1","val2"] ])

But not for a row:

sheet.row(1).value(["val1","val2"]) // →  TypeError: sheet.row(...).value is not a function

I think it would make sense to have value() for  Row too, especially because it's easier to manipulate a row than a range while writing into a file.
For example:

let row=1;
dataArray.forEach(data => {
  sheet.row(row++).value([data.valA, data.valB]);
})

Thanks

Replacing the fsevents dependency?

I installed it with
npm install --save xlsx-populate
on my ubuntu 17.04 with the npm version 3.5.2.

ERROR in ./~/xlsx-populate/lib/Workbook.js
Module not found: Error: Can't resolve 'fs' in '/home/oct/Documents/Workplace/web-app/node_modules/xlsx-populate/lib'
 @ ./~/xlsx-populate/lib/Workbook.js 4:11-24
 @ ./~/xlsx-populate/lib/XlsxPopulate.js
 @ ./src/components/TemplateForm/index.js
 @ ./src/containers/Template/index.js
 @ ./src/containers/index.js
 @ ./src/routes.js
 @ ./src/main.js
 @ multi (webpack)-dev-server/client?http://localhost:3000 webpack/hot/dev-server ./src/main

the reason is the dependency fsevents, since when I try to install it with
npm install --save fsevents
i get

npm ERR! Linux 4.10.0-20-generic
npm ERR! argv "/usr/bin/nodejs" "/usr/bin/npm" "install" "--save" "fsevents"
npm ERR! node v4.7.2
npm ERR! npm  v3.5.2
npm ERR! code EBADPLATFORM

npm ERR! notsup Not compatible with your operating system or architecture: [email protected]
npm ERR! notsup Valid OS:    darwin
npm ERR! notsup Valid Arch:  any
npm ERR! notsup Actual OS:   linux
npm ERR! notsup Actual Arch: x64

npm ERR! Please include the following file with any support request:
npm ERR!     /home/oct/Documents/Workplace/web-app/npm-debug.log

Maybe you want to consider replacing the fsevents dependency with another one which works on all systems?

Sheet dimension range not being updated

It looks like the dimension node in ~/xl/worksheets/sheet1.xml is not being updated to reflect when data is added to the sheet dynamically.

You can see that in the file example-with-image-and-named-cell.xlsx the cell B11 has my old target value of "${data}". Looking at the dimension node for that file, you'll simply see B11 being referenced. The data is then dynamically added to the sheet starting at that cell and expanding out as necessary. In the out.xlsx file, you can see that all the data is there, but inspecting the dimension node it still shows B11.

Let me know if you need any more information. Thanks!

example-with-image-and-named-cell.xlsx
out.xlsx

corrupt files generated

Firstly thank you for a great API.

I have some very basic node code that reads an xlsx template in successfully...modifies it and writes a file out.

The file however cannot be opened in excel, It seems to open fine in googles spreadhseet viewer and libreoffice however. I have tried many permutations of base64encoding the output and that has not helped either.

I have attached a file.
vertrans_template_139.xlsx

Any assistance is appreciated.

"Sheet.definedName" function not working as expected

It would appear that searching for a named cell using the Workbook.definedName function will correctly find it, but attempting to use the Sheet.definedName method will always result in an 'undefined' value being returned. I have included examples to demonstrate.

example-with-image-and-named-cell.xlsx

const xlsxPopulate = require('xlsx-populate');

xlsxPopulate.fromFileAsync('./example-with-image-and-named-cell.xlsx')
            .then(workbook => {
                const sheet = [
                    [1, 2, 3],
                    [4, 5, 6],
                    [7, 8, 9]
                ];

                const worksheet = workbook.sheet(0);
                const rowsCount = (sheet.length - 1);
                const columnCount = (sheet[0].length - 1);
                let cellStartInsert,
                    cellEndInsert,
                    rangeForSheet;

                try {
                    // Update using Workbook object
                    console.log("Updating via Workbook...");
                    cellStartInsert = workbook.definedName("data");
                    cellEndInsert = cellStartInsert.relativeCell(rowsCount, columnCount);
                    rangeForSheet = worksheet.range(cellStartInsert, cellEndInsert);
                    rangeForSheet.value(sheet);
                    console.log("Updating via Workbook... SUCCESS");
                } catch (err) {
                    console.error("Update usig Workbook... FAIL");
                    console.error(err);
                }

                try {
                    // Update using chained Sheet object
                    console.log("Updating via Workbook->Sheet chain...");
                    cellStartInsert = workbook.sheet(0).definedName("data");
                    rangeForSheet = worksheet.range(cellStartInsert, cellEndInsert);
                    rangeForSheet.value(sheet);
                    console.log("Updating via Workbook->Sheet chain... SUCCESS");
                } catch (err) { 
                    console.error("Update using Workbook->Sheet chain... FAIL");
                    console.error(err);
                 }

                try {
                    // Update using Sheet object
                    console.log("Updating via Sheet...");
                    cellStartInsert = worksheet.definedName("data");
                    rangeForSheet = worksheet.range(cellStartInsert, cellEndInsert);
                    rangeForSheet.value(sheet);
                    console.log("Updating via Sheet... SUCCESS");
                } catch (err) { 
                    console.error("Update using Sheet... FAIL");
                    console.error(err);
                 }

                workbook.toFileAsync('./out.xlsx');
            })
            .catch((err) => {
                console.error(err);
            });

Surviving Minified and Uglified

Has anyone had any luck getting the (browser) library to be minified and uglified....

My build process (based on grunt) seems to be breaking something, somewhere...

first error : "n is not defined" at the first line (remembering that n is probably a minified name)

var g = n("../utils")
                  , h = n("./ConvertWorker")
                  , i = n("./GenericWorker")
                  , j = n("../base64")
                  , k = n("../support")
                  , l = n("../external")

which leads to an "Uncaught ReferenceError: XlsxPopulate is not defined" in my code

generating 100k rows in excel crashes the browser

Hi :-) I love this project !

Is it possible to stream the file, instead of inflating the browsers cash ?

I attached some code bellow

thanks a lot :-)

`function doExport(page, options) {
return generate(page, options)
.then(function (blob) {
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
//ie
window.navigator.msSaveOrOpenBlob(blob, page + ".xlsx");
} else {
//not ie
var url = window.URL.createObjectURL(blob);
var a = document.createElement("a");
document.body.appendChild(a);
a.href = url;
a.download = page + ".xlsx";
a.click();
window.URL.revokeObjectURL(url);
document.body.removeChild(a);
}
})
.catch(function (err) {
alert(err.message || err);
throw err;
});
}

function generate(page,options) {
options = options || {};

options.fileName = options.fileName || page;
options.headers = BTB.pages[page].exportData.headers;
options.fields = BTB.pages[page].exportData.fields;
options.data = BTB.pages[page].exportData.rows;
options.lang = options.lang || BTB.language.get();

//prepare headers
var translatedHeaders = []
options.headers.forEach(function (item) {
	var header = BTB.language.dictionary[item] ? BTB.language.dictionary[item][options.lang] : "";
	translatedHeaders.push(header);
});
options.headers = [translatedHeaders];

//prepare data structure for excel
var newData = [];
var newDataLine = [];

options.data.forEach(function (item) {
	newDataLine = [];
	options.fields.forEach(function (field) {
		var newItem = item[field] || "";
		newDataLine.push(newItem);
	})
	newData.push(newDataLine);
});

for (var i = 0; i <= 100000; i++) {
	newData.push(newData[0]);
}

options.newData = newData;

return getWorkbook(options.lang)
	.then(function (workbook) {

		workbook.sheet(0).range("A1:Z1").value(options.headers);
		workbook.sheet(0).range("A2:Z100000").value(options.newData);
		return workbook.outputAsync();//type
	})

}

function getWorkbook(lang) {
lang = lang || "En";
return new Promise(function (resolve, reject) {

	var req = new XMLHttpRequest();
	var url = "/templates/template" + lang + ".xlsx"; //urlInput.value;
	req.open("GET", url, true);
	req.responseType = "arraybuffer";
	req.onreadystatechange = function () {
		if (req.readyState === 4) {
			if (req.status === 200) {
				resolve(XlsxPopulate.fromDataAsync(req.response));
			} else {
				reject("Received a " + req.status + " HTTP code.");
			}
		}
	};

	req.send();
});

}`

Duplicate/add rows with same template

Hi,
I would like to propose a possible enhancement. It would be fine to duplicate a row with a given template by adding the same row in the following rows. Is it already possible in some way? Is there something similar in your roadmap?

Thank you for your work!

Output file loses data and formatting

Hi,

I'm modifying a large file with several sheets, I modify the value of one cell and save it to file. The modified sheet contains only a couple of column headings and nothing else.

This lib is the closest I've found to matching my requirements though, it preserves the macros and other data in the file perfectly.

What can I do to help debug it?

Issue when creating a new Sheet

Using the following code

var sheetNode = parser.parseFromString('<sheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" name="' + worksheetname + '" sheetId="1"/>').documentElement;
var sheetXML = parser.parseFromString('<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><sheetData><row r="1"/></sheetData></worksheet>').documentElement;
worksheet = new Sheet(workbook, sheetNode, sheetXML);
worksheet.setName(worksheetname);
console.log('creating a new worksheet', workbook.getSheet(worksheetname).getName());              

everything works untill last line where the new sheet does not seem to be attached to the workbook...

Cannot instead any value to excel file

const XlsxPopulate = require('xlsx-populate');
XlsxPopulate.fromFileAsync("myfile.xlsx")
.then(workbook => {
const r = workbook.sheet(0).range("D2:D50");
r.value(55);
var q = 4;
sheet(0).cell("D4").value(q.toString());
});

None of these two works while trying to insert value(s) into excel

Find method match results alternately

In a worksheet, inserting the same text into several cells by using the "find" method of the worksheet, only a few cells are identified, it seems that the problem is due to the "/ g" the regex object will save state between calls.
Possible workaround in use _.clone(pattern) into regexify.js instead of using the old object, but I don't know if it is the best solution,

Could example download from Express router?

Could example download from Express router?
I tried but don't work (bas on Meteor Js)

// Server
var express = require('express');
var app = express();

// respond with "hello world" when a GET request is made to the homepage
app.get('/express', function (req, res, next) {
    console.log('express');
    let templateFile = Meteor.absolutePath + '/private/template.xlsx';

    // Open the workbook.
    XlsxPopulate.fromFileAsync(templateFile)
        .then(workbook => {
            // Make edits.
            workbook.sheet(0).cell("A1").value("foo");

            // Get the output
            return workbook.outputAsync();
        })
        .then(data => {
            // Set the output file name.
            res.attachment("output.xlsx");

            // Send the workbook.
            res.send(data);
        })
        .catch(next);
});

WebApp.connectHandlers.use(app); // Config express + meteor js
----------
// Client
                axios.get('/express', {}).then((res) => {
                    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
                        // If IE, you must uses a different method.
                        window.navigator.msSaveOrOpenBlob(blob, "out.xlsx");
                    } else {
                        var url = window.URL.createObjectURL(res);
                        var a = document.createElement("a");
                        document.body.appendChild(a);
                        a.href = url;
                        a.download = "out.xlsx";
                        a.click();
                        window.URL.revokeObjectURL(res);
                        document.body.removeChild(a);
                    }
                }).catch((error) => {
                    console.log(error);
                });

Get error

post.vue:52 TypeError: Failed to execute 'createObjectURL' on 'URL': No function was found that matched the signature provided.
    at post.vue:42
    at meteor.js?hash=27829e9…:1105
    at <anonymous>

Returning wrong font color

Hi dtjohnson ,
Thank you very much for your xlsx-populate module. I am able to get cell values from excel sheet but when I retrieving the font color of cell it returning wrong color. for example I retrieving font color from a cell it has red color but it returning yellow. Could you please take a look ?.
Please let me know if you want more information.
Regards,
Durga Prasad

Could example to generate and download `excel file` from `exsiting template` in `Meteor JS`?

I base on Meteor.
I used to https://github.com/SheetJS/js-xlsx + FileSaver` to write and download.

// Meteor method (server)
Meteor.methods({
    downloadExcel (){
        if (!this.isSimulation) {
            /* this is the data we ultimately want to save */
            const data = [
                ["a", "b", "c"],
                [1, 2, 3]
            ];
            /* follow the README to see how to generate a workbook from the data */
            const ws = XLSX.utils.aoa_to_sheet(data);
            const wb = {SheetNames: ["Sheet1"], Sheets: {Sheet1: ws}};
            /* send workbook to client */
            return wb;
})
---------
// Client
            handleWrite() {
                let self = this;

                Meteor.call('downloadExcel', function (err, wb) {
                    if (err) {
                        console.error(err);
                    } else {
                        /* "Browser download file" from SheetJS README */
                        var wopts = {bookType: 'xlsx', bookSST: false, type: 'binary'};
                        var wbout = XLSX.write(wb, wopts);
                        saveAs(new Blob([self.s2ab(wbout)], {type: "application/octet-stream"}), "meteor.xlsx");
                    }
                });
            },

-------
funciton 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;
            }

Could you example for this package with Meteor?

An option for numberToDate to indicate what should the date be accurate to

Hi.
095959.xlsx
As the file shows in Excel, B2 is 10:00:00, but it is actually 09:59:59.995 and Excel rounds the value to 10:00:00 because B2's number format doesn't include milliseconds.

Converted by numberToDate, the date instance's getters of hours/minutes/seconds return 09/59/59, which is different from what users see in Excel.

So it might be useful to have an option for numberToDate to indicate that what should the date be accurate to.

Write data with keep format of cell

I have template file with some settings at the format for cells. (e.g the cell "A1" have been setting as "Currency") but when write data with:
var workbook = Workbook.fromFileSync("./Template1.xlsx"); workbook.getSheet("Sheet1").getCell(1,1).setValue(1000); workbook.toFileSync("./out.xlsx");
After success the format at cell "A1" of out.xlsx have been changed to "General". How can I keep the format of cell as Template file?

Thanx.

When I try to ad a value to a Cell it prints undefined

Hi,
I'm trying to add some dynamic values to new cells like this
this._worksheet.cell("H7").value(dynVal);

I double check dynVal and I have a value but when I try to see the value inserted I got a 'undefined'
I made sure that dynVal was a string.

Any ideas?

Thanks

how do I read cell Value?

var Workbook = require('xlsx-populate');

// Load the input workbook from file.
var workbook = Workbook.fromFileSync("./Book1.xlsx");

// Modify the workbook.
workbook.getSheet("Sheet1").getCell("A1")

returns a giant object. how do I get the value of cell A1?

Automatically set column-width to "fit" data

Is this already a feature in the project, or is there a pattern you would suggest, that would make it so the columns of the generated spreadsheet "fit" their largest piece of data? This same behavior can be achieved in Excel by double-clicking on the right-hand edge of a column-header (after it turns into the resize cursor).

I'm positive that I will be able to get this result using the methods you've already provided in the API, but I figured I'd ask if you had any suggestions first before I start getting into it.

Thanks!

workbook.toFileAsync chaining with .then

I am trying to call a function after the sheet has been saved but this doesn't work.

Without the .then included, the sheet is saved without an problems.

XlsxPopulate.fromFileAsync(file)
                .then(workbook => {

                    const values = workbook.sheet("Sheet1").usedRange().value();
                    workbook.sheet("Sheet1").cell(values.length + 1, 1).value(config.ReportDate);
                    workbook.sheet("Sheet1").cell(values.length + 1, 2).value(config.ReportLength);
                
                   return workbook.toFileAsync("./SP_reports/JB Report_" + config.ReportDate + ".xls")
                        .then(function () {
                        addTextToSpan('JB report updated', 'info')
                        uploadReport();
                        // })


                })
                .catch(function (err) {
                    console.log('something bad has happened', err);
                })

Any ideas? :)

Multiple styles within a cell

Hi,

Great work, but just ran into a limitation perhaps. Can you have multiple styles within a cell? Such as, within a single cell, a sentence of text that is black, and a sentence of text that is red?

Thanks!

  • Jesse

`Workbook.copySheet()`

Our use case:
We have a template xlsx sheet (with e.g. a logo); We would like this template to be used for all added sheets so the logo appears on all sheets.

How do I get 01 as a string

I'm trying to get a value from a cell that is "01" but when I use ... row("A7").value() it will return a number 1 and I want to retrieve "01" as a string
Any idea ?

Thanks

file size increases drastically

Thanks a ton for the wonderful API.

I am using xlsx-populate to modify few cells in an existing file (xlsm) and writing it to another xlsm file. This is a node.js application. The template file is 100kb. The new file generated with toFile() method is 700kb with only 3 fields/cells modified. I am using version 0.8.0 of the API. In addition, I have tried using the newer version (1.x) but that results in a corrupt file. Any help is deeply appreciated. Thanks!
Code looks similar to below:

xlsxPopulate.fromFile(fileName, (error, workbook) => {
if(error) { //log }
else{
workbook.getSheet(sheetname).getCell(cellname).value(newVal);
xlsxPopulate.toFile(outfile);
}

Worksheet length ?

Is there any way to know from a worksheet, the last row that has a value ?

I want to add new values to new rows but first I will need to know witch row is the last one

blank sheet

I load a sheet with colors, formatting, formula.
I change some text in cell in a sheet and save in same path as load.
I change again some things in same sheet, other cells.
When i save this time, no problem, but when open the file, Excel say me it's broken and go repair. And my sheet is blank, all others are ok.

The first time, all is ok.

Have problem with recored 10000+?

I try to generate for exist file template, and insert records 10000+.
I have problem with download (don't complete).
And then I open file download

image

My code

// Meteor method server
Meteor.methods({
    async postExcelReport(){
        if (Meteor.isServer) {
            // Template file
            let templateFile = Meteor.absolutePath + '/private/template.xlsx';

            // Load an existing workbook
            let wb = await XlsxPopulate.fromFileAsync(templateFile);
            let sheet = wb.sheet("Sheet1");

            // Data
            let data = Posts.find({});
            let startRow = 6;
            let row = 0;
            for (let index = 0; index < 10000; index++) {
                row = startRow + index;

                sheet.cell(`A${row}`).value(index);
                sheet.cell(`B${row}`).value('title');
                sheet.cell(`C${row}`).value('body');
                sheet.cell(`D${row}`).value('type');
                sheet.cell(`E${row}`).value('true');
                sheet.cell(`F${row}`).value('date');
                sheet.cell(`G${row}`).value(100);
            }

            // Footer
            let lastRow = row + 1;
            sheet.range(`A${lastRow}:F${lastRow}`)
                .merged(true).value('Total: ')
                .style({bold: true, horizontalAlignment: 'right'});
            sheet.cell(`G${lastRow}`).formula(`=SUM(G${startRow}:G${row})`);

            // Style
            sheet.range(`Annb${startRow}:G${lastRow}`).style({border: true});

            // Write to file.
            return wb.outputAsync("base64");
        }
    },
});
-----------------
// Client
                Meteor.call('postExcelReport', {type: 'Education'}, function (err, res) {
                    location.href = "data:" + XlsxPopulate.MIME_TYPE + ";base64," + res;
                });

In browse console
image

Writing to cells becomes corrupt

When I run the following code and open the file, it appears that column B is becoming corrupt and lost. Using a new workbook or an existing one has the same problem.

for (var idxRow = 0; idxRow < 30; idxRow++) { for (var idxColumn = 0; idxColumn < 30++) { workbook.sheet(0).cell(7 + idxRow, idxColumn).value("Row: " + idxRow.toString() + " Column: " + idxColumn.toString()); } }

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.