Skip to content

Commit 7db69ac

Browse files
committed
#129 autofit xlsx column width on export
1 parent 12ac4b9 commit 7db69ac

2 files changed

Lines changed: 18 additions & 1 deletion

File tree

serverless/app/handlers/__tests__/export.test.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ jest.mock('../../../lib/StorageClient', () => ({
1717
jest.mock('xlsx', () => ({
1818
utils: {
1919
book_new: jest.fn(),
20-
json_to_sheet: jest.fn(),
20+
json_to_sheet: jest.fn().mockReturnValue({}),
2121
book_append_sheet: jest.fn(),
2222
},
2323
write: jest.fn().mockReturnValue(Buffer.from('mock-excel-content')),

serverless/app/handlers/export.ts

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,23 @@ export const handler: APIGatewayProxyHandler = async event => {
126126
// Create workbook and worksheet
127127
const wb = XLSX.utils.book_new();
128128
const ws = XLSX.utils.json_to_sheet(rows);
129+
130+
// Auto-fit columns
131+
if (rows.length > 0) {
132+
const headers = Object.keys(rows[0]);
133+
const colWidths = headers.map(key => {
134+
let maxLength = key.length;
135+
rows.forEach(row => {
136+
const val = row[key as keyof ExportRow];
137+
const len = val ? String(val).length : 0;
138+
if (len > maxLength) maxLength = len;
139+
});
140+
// Cap the width at 50 to prevent massive columns, but ensure at least 10
141+
return { wch: Math.min(Math.max(maxLength + 2, 10), 50) };
142+
});
143+
ws['!cols'] = colWidths;
144+
}
145+
129146
XLSX.utils.book_append_sheet(wb, ws, 'Cases');
130147

131148
// Generate buffer

0 commit comments

Comments
 (0)