Unity 在word中插入图片 并向word表格中写入数据

首先是借鉴的这位大佬的博客:C#操作Word,写数据,插入图片 - Sealee - 博客园

要将Aspose.Words.dll文件放在unity工程中的Plugins文件夹下,并在工程中引入

在word中新建书签与表格

 private string filePath;
    private string filePathColne;
    private string imagePath; //图片路径
    private Document doc;
    private DocumentBuilder builder;
    private string tempStr;
    
    void Start()
    {
        tempStr = "D:\\PrintImage/20210922151659.jpg";
        imagePath = null;
        filePath = "D:\\PrintWord/PrintWord.doc";
        filePathColne = "D:\\PrintWord/PrintWordColbe.doc";
        File.Copy(filePath, filePathColne, true);                 //必须复制一个word出来,不然会报错
        File.SetAttributes(filePathColne, FileAttributes.Normal); //设置复制出来的文件的属性 只读 还是可修改
        doc = new Document(filePathColne);
    }

    private void WriteImage(string imgPath)
    {
        builder = new DocumentBuilder(doc);
        builder.MoveToBookmark("img");       //定位img书签的位置,(大佬博客中的说法),我试着删除书签后,结果是直接在word第一行中插入图片
        FileStream fs = new FileStream(imgPath, FileMode.Open);   //读取图片,并以byte[]的方式写入
        byte[] imageByte = new byte[fs.Length];
        fs.Read(imageByte, 0, imageByte.Length);
        builder.InsertImage(imageByte, 400, 400);
        fs.Close();
        WriteExcel();//调用插入表格数据的方法
        builder = null;
        doc.Save(filePathColne);
    }

    private void WriteExcel()
    {
        NodeCollection allTables = doc.GetChildNodes(NodeType.Table, true);  //获取所有表格
        Table table = allTables[0] as Table;                                 //获取第一个表格
        var row = table.Rows[table.Rows.Count - 1];                          //在表格的最后一行插入数据
        builder.MoveToCell(0, table.Rows.Count - 1, 0, 0);                   //移动到单元格第几行第几列
        builder.Write("菜鸡");                                               //写入数据
        builder.MoveToCell(0, table.Rows.Count - 1, 1, 0);
        builder.Write("菜鸡");
        builder.MoveToCell(0, table.Rows.Count - 1, 2, 0);
        builder.Write("菜鸡");
        builder.MoveToCell(0, table.Rows.Count - 1, 3, 0);
        builder.Write("菜鸡");
        builder.MoveToCell(0, table.Rows.Count - 1, 4, 0);
        builder.Write("菜鸡");
        builder.MoveToCell(0, table.Rows.Count - 1, 5, 0);
        builder.Write("菜鸡");
        builder.MoveToCell(0, table.Rows.Count - 1, 6, 0);
        builder.Write("菜鸡");
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.O))
        {
            WriteImage(tempStr);
        }
    }

这个是效果图

 Aspose.Words.dll文件可以在网上搜索下载

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值