使用excel4node向excel批量写入图片

import fs from 'fs';

import path from 'path';

import xl from "excel4node";

// 创建一个新的工作簿

const wb = new xl.Workbook();

// 添加一个工作表

const ws = wb.addWorksheet('Sheet 1');

// 指定要读取的文件夹路径

const directoryPath = 'G://测试'; // 替换为你的文件夹路径

let i = 1;

const putImg = (ws, file) => {

    ws.row(i).setHeight(200); // 设置每行的行高为50

    ws.column(i).setWidth(40);


 

    ws.addImage({

        path: 'G://测试//' + file,

        type: 'picture',

        position: {

            type: 'twoCellAnchor',

            from: {

                col: 1,

                colOff: 0,

                row: i,

                rowOff: 0,

            },

            to: {

                col: 2,

                colOff: 0,

                row: i + 1,

                rowOff: 0,

            },

        },

    });

    i++;

}

// 使用同步方法读取文件夹

try {

    const files = fs.readdirSync(directoryPath);

    files.forEach(file => {

        // 获取文件的完整路径

        const filePath = path.join(directoryPath, file);

        // 使用fs.statSync检查是文件还是目录

        const stats = fs.statSync(filePath);

        if (stats.isFile() && file.startsWith("1074118")) {

            console.log(`File: ${file}`);

            let name = file.split(".")[0]

            ws.cell(i,2).string(name)

            // 将图片放入excel

            putImg(ws, file)

           

        } else if (stats.isDirectory()) {

            // console.log(`Directory: ${file}`); // 你可以递归地读取子目录

        }

    });

    // 将工作簿保存到文件

    wb.write('document_with_image.xlsx', (err, stats) => {

        if (err) {

            console.error('出现错误:', err);

        } else {

            console.log('带有图片的Excel文档已创建');

        }

    });

} catch (err) {

    console.error(`Unable to scan directory: ${err}`);

}

你可能感兴趣的:(javascript,前端,vue.js)