exceljs icon indicating copy to clipboard operation
exceljs copied to clipboard

[F] Add insertColumns() function

Open johnpeb opened this issue 3 years ago • 2 comments

🚀 Feature Proposal

Similar to the existing worksheet.insertRows() it would be useful to have the corresponding method for columns.

Motivation

I'd like to insert columns with styles, similar to how I do so with rows.

Example

worksheet.insertColumns(colNum, newColData, 'i+')

johnpeb avatar Dec 20 '21 19:12 johnpeb

Here's my workaround, inspired by insertRows

import Excel = require('exceljs')

export function insertColumns (worksheet: Excel.Worksheet, pos: number, values: object[][], style = 'n'): void {
  worksheet.spliceColumns(pos, 0, ...values)
  if (style !== 'n') {
    // copy over the styles
    for (let i = 0; i < values.length; i++) {
      if (style[0] === 'o' && worksheet.getColumn(values.length + pos + i) !== undefined) {
        copyStyle(worksheet, values.length + pos + i, pos + i, style[1] === '+')
      } else if (style[0] === 'i' && worksheet.getColumn(pos - 1) !== undefined) {
        copyStyle(worksheet, pos - 1, pos + i, style[1] === '+')
      }
    }
  }
}

function copyStyle (worksheet: Excel.Worksheet, src: number, dest: number, styleEmpty = false): void {
  const cSrc = worksheet.getColumn(src)
  const cDst = worksheet.getColumn(dest)
  cDst.style = cSrc.style // copyStyle(cSrc.style)

  cSrc.eachCell({ includeEmpty: styleEmpty }, (cell, rowNumber: number) => {
    worksheet.getCell(rowNumber, dest).style = cell.style // copyStyle(cell.style)
  })
  cDst.width = cSrc.width
}

johnpeb avatar Dec 20 '21 19:12 johnpeb

Any update?

mfarchana avatar Aug 09 '22 07:08 mfarchana

I run into this problblem and made my one whery similar workaround like johnpeb But i have to admit that this workaround doesn't deal with formulas etc. So it's not triggering them to change, neither it moves selection lists for cells. And on any not really simple worksheet all this causes confusion. So, any ideas how to achive proper column inserting?

verberden avatar Dec 09 '22 14:12 verberden