How to set cell width when export .xlsx files with js-xlsx

后端 未结 6 1328
南笙
南笙 2021-02-01 14:50

I am trying to set a fixed column/cell width to my exported excel files with js-xlsx.

EDIT:

Here is the source of js-xlsx: https://github.com/SheetJS/js-xlsx

6条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-01 15:21

    I used @Icycool 's answer as great example. I also upvoted that one as it was very useful for me.

    I enhanced it a bit with a configurable default width if the content is smaller than the title and added a buffer so that it doesn't look crammed together.

    Added comments and expanded to increase readability

     return Object.keys(dataSource[0][0]).map((key) => {
      return ({
        //pick the data value that has the most content
        wch: Math
          .max(...dataSource[0]
    
            //Iterate over the column object and return a width for each one
            .map((dataObj: any) => {
    
              //Return the width as the number of chars with a buffer
              let keyWidth = key.toString().length
              let width = dataObj[key]?.toString().length ?? defaultColumnWidth
              width = width + columnWidthBuffer
    
              //use a default with if it's smaller than the title
              if (width < keyWidth) {
                width = keyWidth
              }
              return width
            })
          )
      })
    });
    

提交回复
热议问题