用js将base64图片导入到xlsx文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Export Excel with Images</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/exceljs/4.2.0/exceljs.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js"></script>
</head>
<body>
    <button onclick="exportExcel()">Export to Excel</button>

    <script>
        async function exportExcel() {
            const workbook = new ExcelJS.Workbook();
            const worksheet = workbook.addWorksheet('Sheet1');

            // Add headers
            worksheet.columns = [
                { header: 'ID', key: 'id', width: 10 },
                { header: 'Name', key: 'name', width: 32 },
                { header: 'Picture', key: 'picture', width: 32 }
            ];

            // Example data
            const data = [
                { id: 1, name: 'Alice', image: "data:image/png;base64,iVB..." }, // Replace with your base64 image data
                { id: 2, name: 'Bob', image: "data:image/png;base64,iVB..." },
                { id: 3, name: 'Charlie', image: "data:image/png;base64,iVB..." }
            ];

            // Add data to worksheet
            data.forEach((item, index) => {
                const rowIndex = index + 2; // Start from the second row
                worksheet.addRow({ id: item.id, name: item.name });

                // Add the image to the worksheet
                if (item.image.startsWith('data:image/')) {
                    const imageId = workbook.addImage({
                        base64: item.image,
                        extension: 'png'
                    });

                    worksheet.addImage(imageId, {
                        tl: { col: 2, row: rowIndex - 1 },
                        ext: { width: 100, height: 100 }
                    });
                }
            });

            // Generate Excel file
            const buffer = await workbook.xlsx.writeBuffer();

            // Save Excel file
            const blob = new Blob([buffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
            saveAs(blob, 'example_with_images.xlsx');
        }
    </script>
</body>
</html>

 

posted @ 2024-08-06 11:53  惊蛰丶  阅读(95)  评论(0编辑  收藏  举报