Created
June 8, 2021 02:53
-
-
Save ShinChven/16265da683ff397471a2fe8a6f48d7b0 to your computer and use it in GitHub Desktop.
exceljs auto adjust column width
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ExcelJS, {Worksheet} from "exceljs"; | |
/** | |
* Autofit columns by width | |
* | |
* @param worksheet {ExcelJS.Worksheet} | |
* @param minimalWidth | |
*/ | |
export const autoWidth = (worksheet: Worksheet, minimalWidth = 10) => { | |
worksheet.columns.forEach((column) => { | |
let maxColumnLength = 0; | |
if (column && typeof column.eachCell === 'function') { | |
column.eachCell({includeEmpty: true}, (cell) => { | |
maxColumnLength = Math.max( | |
maxColumnLength, | |
minimalWidth, | |
cell.value ? cell.value.toString().length : 0 | |
); | |
}); | |
column.width = maxColumnLength + 2; | |
} | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment