Skip to content

Instantly share code, notes, and snippets.

@ShinChven
Created June 8, 2021 02:53
Show Gist options
  • Save ShinChven/16265da683ff397471a2fe8a6f48d7b0 to your computer and use it in GitHub Desktop.
Save ShinChven/16265da683ff397471a2fe8a6f48d7b0 to your computer and use it in GitHub Desktop.
exceljs auto adjust column width
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