1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
|
// lib/utils/export-to-excel.ts
import ExcelJS from 'exceljs'
interface ExportToExcelOptions {
filename?: string
sheetName?: string
headers?: string[]
dateFormat?: string
autoFilter?: boolean
freezeHeader?: boolean
}
/**
* 데이터 배열을 Excel 파일로 내보내기 (ExcelJS 사용)
* @param data - 내보낼 데이터 배열
* @param options - 내보내기 옵션
*/
export async function exportDataToExcel(
data: Record<string, any>[],
options: ExportToExcelOptions = {}
) {
const {
filename = 'export',
sheetName = 'Sheet1',
headers,
dateFormat = 'yyyy-mm-dd',
autoFilter = true,
freezeHeader = true
} = options
try {
// 데이터가 없으면 반환
if (!data || data.length === 0) {
console.warn('No data to export')
return false
}
// 워크북 생성
const workbook = new ExcelJS.Workbook()
workbook.creator = 'TBE System'
workbook.created = new Date()
// 워크시트 추가
const worksheet = workbook.addWorksheet(sheetName, {
properties: {
defaultRowHeight: 20
}
})
// 헤더 처리
const finalHeaders = headers || Object.keys(data[0])
// 컬럼 정의
const columns = finalHeaders.map(header => ({
header,
key: header,
width: Math.min(
Math.max(
header.length,
...data.map(row => {
const value = row[header]
if (value === null || value === undefined) return 0
return String(value).length
})
) + 2,
50
)
}))
worksheet.columns = columns
// 데이터 추가
data.forEach(row => {
const rowData: Record<string, any> = {}
finalHeaders.forEach(header => {
const value = row[header]
// null/undefined 처리
if (value === null || value === undefined) {
rowData[header] = ''
}
// Date 객체 처리
else if (value instanceof Date) {
rowData[header] = value
}
// boolean 처리
else if (typeof value === 'boolean') {
rowData[header] = value ? 'Yes' : 'No'
}
// 숫자 처리
else if (typeof value === 'number') {
rowData[header] = value
}
// 기타 (문자열 등)
else {
rowData[header] = String(value)
}
})
worksheet.addRow(rowData)
})
// 헤더 스타일링
const headerRow = worksheet.getRow(1)
headerRow.font = { bold: true }
headerRow.fill = {
type: 'pattern',
pattern: 'solid',
fgColor: { argb: 'FFE0E0E0' }
}
headerRow.alignment = { vertical: 'middle', horizontal: 'center' }
headerRow.height = 25
// 헤더 테두리
headerRow.eachCell((cell) => {
cell.border = {
top: { style: 'thin' },
left: { style: 'thin' },
bottom: { style: 'thin' },
right: { style: 'thin' }
}
})
// 데이터 행 스타일링
worksheet.eachRow((row, rowNumber) => {
if (rowNumber > 1) {
row.alignment = { vertical: 'middle' }
row.eachCell((cell) => {
cell.border = {
top: { style: 'thin' },
left: { style: 'thin' },
bottom: { style: 'thin' },
right: { style: 'thin' }
}
})
}
})
// 자동 필터 추가
if (autoFilter) {
worksheet.autoFilter = {
from: { row: 1, column: 1 },
to: { row: data.length + 1, column: columns.length }
}
}
// 헤더 고정
if (freezeHeader) {
worksheet.views = [
{ state: 'frozen', ySplit: 1 }
]
}
// 날짜 포맷 적용
worksheet.eachRow((row, rowNumber) => {
if (rowNumber > 1) {
row.eachCell((cell, colNumber) => {
const header = finalHeaders[colNumber - 1]
const value = data[rowNumber - 2][header]
if (value instanceof Date) {
cell.numFmt = dateFormat === 'yyyy-mm-dd'
? 'yyyy-mm-dd'
: 'mm/dd/yyyy'
}
// 숫자 포맷 (천단위 구분)
else if (typeof value === 'number' && header.toLowerCase().includes('quantity')) {
cell.numFmt = '#,##0'
}
})
}
})
// 파일 다운로드
const buffer = await workbook.xlsx.writeBuffer()
const blob = new Blob([buffer], {
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
})
const url = URL.createObjectURL(blob)
const link = document.createElement('a')
const timestamp = new Date().toISOString().slice(0, 10)
const finalFilename = `${filename}_${timestamp}.xlsx`
link.href = url
link.download = finalFilename
link.style.display = 'none'
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
URL.revokeObjectURL(url)
return true
} catch (error) {
console.error('Excel export error:', error)
throw new Error('Failed to export Excel file')
}
}
/**
* Date 객체를 Excel 형식으로 포맷팅
*/
function formatDateForExcel(date: Date, format: string): string {
const year = date.getFullYear()
const month = String(date.getMonth() + 1).padStart(2, '0')
const day = String(date.getDate()).padStart(2, '0')
switch (format) {
case 'yyyy-mm-dd':
return `${year}-${month}-${day}`
case 'dd/mm/yyyy':
return `${day}/${month}/${year}`
case 'mm/dd/yyyy':
return `${month}/${day}/${year}`
default:
return date.toLocaleDateString()
}
}
/**
* CSV 파일로 내보내기 (대안 옵션)
*/
export function exportDataToCSV(
data: Record<string, any>[],
filename: string = 'export'
) {
try {
if (!data || data.length === 0) {
console.warn('No data to export')
return
}
// 헤더 추출
const headers = Object.keys(data[0])
// CSV 문자열 생성
let csvContent = headers.join(',') + '\n'
data.forEach(row => {
const values = headers.map(header => {
const value = row[header]
// null/undefined 처리
if (value === null || value === undefined) return ''
// 콤마나 줄바꿈이 있으면 따옴표로 감싸기
const stringValue = String(value)
if (stringValue.includes(',') || stringValue.includes('\n')) {
return `"${stringValue.replace(/"/g, '""')}"`
}
return stringValue
})
csvContent += values.join(',') + '\n'
})
// BOM 추가 (Excel에서 UTF-8 인식)
const BOM = '\uFEFF'
const blob = new Blob([BOM + csvContent], { type: 'text/csv;charset=utf-8;' })
// 다운로드 링크 생성
const link = document.createElement('a')
const url = URL.createObjectURL(blob)
link.setAttribute('href', url)
link.setAttribute('download', `${filename}_${new Date().toISOString().slice(0, 10)}.csv`)
link.style.visibility = 'hidden'
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
return true
} catch (error) {
console.error('CSV export error:', error)
throw new Error('Failed to export CSV file')
}
}
/**
* 간단한 데이터 내보내기 헬퍼
* Excel이 안되면 CSV로 fallback
*/
export async function exportData(
data: Record<string, any>[],
options: ExportToExcelOptions & { format?: 'excel' | 'csv' } = {}
) {
const { format = 'excel', ...exportOptions } = options
try {
if (format === 'csv') {
return exportDataToCSV(data, exportOptions.filename)
} else {
return exportDataToExcel(data, exportOptions)
}
} catch (error) {
console.error(`Failed to export as ${format}, trying CSV as fallback`)
// Excel 실패 시 CSV로 시도
if (format === 'excel') {
try {
return exportDataToCSV(data, exportOptions.filename)
} catch (csvError) {
console.error('Both Excel and CSV export failed')
throw csvError
}
}
throw error
}
}
|