Skip to content

Instantly share code, notes, and snippets.

@tungd
Last active October 11, 2018 10:43
Show Gist options
  • Save tungd/587f7dbbcb4f738eeac8b9c6d8e35512 to your computer and use it in GitHub Desktop.
Save tungd/587f7dbbcb4f738eeac8b9c6d8e35512 to your computer and use it in GitHub Desktop.
const xlsx = require('xlsx')
const table = xlsx.readFile('sample.xlsx', { cellStyles: true })
const sheet = table.Sheets[table.SheetNames[0]];
console.log(sheet)
// sheet['C10'] = { t: 's', v: 'Test update value' }
const addCell = (sheet, cell, value) => {
sheet[cell] = Object.assign({}, sheet[cell], value)
const range = xlsx.utils.decode_range(sheet['!ref'])
const address = xlsx.utils.decode_cell(cell)
if (range.s.c > address.c) range.s.c = address.c
if (range.s.r > address.r) range.s.r = address.r
if (range.e.c < address.c) range.e.c = address.c
if (range.e.r < address.r) range.e.r = address.r
sheet['!ref'] = xlsx.utils.encode_range(range)
}
const setColumnStyle = (sheet, column, style) => {
const cols = sheet['!cols'] || []
const columnNumber = xlsx.utils.decode_col(column)
for (let i = cols.length; i < columnNumber; i += 1) {
cols.push({})
}
cols[columnNumber] = Object.assign({}, cols[columnNumber], style)
sheet['!cols'] = cols
}
addCell(sheet, 'C10', { t: 's', v: 'Test update value' })
setColumnStyle(sheet, 'E', { hidden: true })
// console.log(sheet['!cols'])
// sheet['!colBreaks'] = [2, 4]
xlsx.writeFile(table, 'changed.xlsx')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment