dtjohnson / xlsx-populate

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.
MIT License
956 stars 183 forks source link

How to get last column of specific row? #298

Closed quangtho2910 closed 3 years ago

quangtho2910 commented 3 years ago

I know we can use usedRange().endcell().columnNumber() to get the last column of workbook. But I want to get the last column of specific row. Can we do that in xlsx-populate?

Akxe commented 3 years ago

Excel does not store this information... you can get the last item of row by row._rows[row._rows.length - 1], but this is not 100%. It will give you the last cell with its own value. This excludes cells that are merged.

quangtho2910 commented 3 years ago

@Akxe I tried workbook.sheet("Sheet1").row(1)._rows[row(1)._rows.length - 1] But I got an error

row is not defined

Akxe commented 3 years ago

You did not make the row variable... you have to define it...

const row = workbook.sheet("Sheet1").row(1);
row._rows[row._rows.length - 1];
quangtho2910 commented 3 years ago

@Akxe Thank you but still the same ...

Cannot read property 'length' of undefined

quangtho2910 commented 3 years ago

Here is my code:

XlsxPopulate.fromFileAsync("Filename")
.then(workbook => {
    const row = workbook.sheet("Sheet1").row(1);
    console.log(row._rows[row._rows.length - 1])
});
Akxe commented 3 years ago

Are you sure that there is "Sheet1" in workbook.sheet()?

quangtho2910 commented 3 years ago

Yes, I am sure. If there is no "Sheet1" the error would be "Cannot read property 'row' of undefined". Not "Cannot read property 'length' of undefined"

quangtho2910 commented 3 years ago

I found the way @Akxe The code should be: XlsxPopulate.fromFileAsync("Filename") .then(workbook => { const row = workbook.sheet("Sheet1").row(1); console.log(row._cells[row._cells.length - 1]._columnNumber) });

Akxe commented 3 years ago

Then it is because the row does not have any columns... From what I remember there is a lot of lazy defining of internal variables.

Hmm... Rows of row... The whole time you should be getting _cells

quangtho2910 commented 3 years ago

Yes, my code works so I think that is the way to get the last column of the specific row. Thank you so much @Akxe . Based on your answer I found a way to solve my problem!

Akxe commented 3 years ago

Please close the issue then 😊