47 lines
1.4 KiB
TypeScript
47 lines
1.4 KiB
TypeScript
import { NextResponse } from 'next/server';
|
|
import * as XLSX from 'xlsx';
|
|
|
|
export async function POST(request: Request) {
|
|
try {
|
|
const { data } = await request.json();
|
|
|
|
// Create a new workbook
|
|
const wb = XLSX.utils.book_new();
|
|
|
|
// Process each document's data
|
|
data.forEach((doc: any, index: number) => {
|
|
// Create worksheet for the main data
|
|
const mainData = {
|
|
Company: doc.company,
|
|
Address: doc.address,
|
|
'Total Sum': doc.total_sum,
|
|
};
|
|
const mainWS = XLSX.utils.json_to_sheet([mainData]);
|
|
|
|
// Create worksheet for items
|
|
const itemsWS = XLSX.utils.json_to_sheet(doc.items);
|
|
|
|
// Add worksheets to workbook
|
|
XLSX.utils.book_append_sheet(wb, mainWS, `Doc${index + 1} Summary`);
|
|
XLSX.utils.book_append_sheet(wb, itemsWS, `Doc${index + 1} Items`);
|
|
});
|
|
|
|
// Generate Excel file buffer
|
|
const excelBuffer = XLSX.write(wb, { type: 'buffer', bookType: 'xlsx' });
|
|
|
|
// Return the Excel file as a response
|
|
return new NextResponse(excelBuffer, {
|
|
headers: {
|
|
'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
|
'Content-Disposition': 'attachment; filename="extracted_data.xlsx"',
|
|
},
|
|
});
|
|
} catch (error) {
|
|
console.error('Error generating Excel file:', error);
|
|
return NextResponse.json(
|
|
{ error: 'Failed to generate Excel file' },
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
}
|