You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将动态生成的图片导出填充至MS Word模板的指定表格中

解决方案

前置准备(Word模板调整)

  • 打开模板文件D:\BASE\1.docx,找到用于存放图片的目标表格,在需要插入图片的单元格内分别输入占位符 {Image1}、{Image2}、{Image3},占位符位置可根据你的排版需求自定义。

代码修改

1. 修正截图存储文件名逻辑

原代码中保存的图片文件名和动态生成的PictureBox名称不匹配,调整btn_scrennshot_Click方法内的图片保存逻辑:

// 原保存代码替换为以下内容
string path = @"D:\BASE\Images";
string fileName = $"{textBox_3.Text}{DateTime.Now.Hour}{DateTime.Now.Minute}{DateTime.Now.Second}.jpeg";
pictureBox1.Image.Save(Path.Combine(path, fileName), ImageFormat.Jpeg);
// 同时修改PictureBox的Name属性,和文件名匹配
pb.Name = fileName;

2. 新增图片占位符替换方法

新增专门用于将占位符替换为图片的方法:

private void ReplaceStubWithImage(string stubToReplace, string imagePath, Word.Document wordDocument, float width = 200, float height = 150)
{
    Word.Range range = wordDocument.Content;
    range.Find.ClearFormatting();
    // 查找占位符
    if (range.Find.Execute(FindText: stubToReplace))
    {
        // 删除占位符文本
        range.Text = string.Empty;
        // 插入图片,设置为嵌入型适配单元格
        Word.InlineShape img = range.InlineShapes.AddPicture(
            FileName: imagePath,
            LinkToFile: false,
            SaveWithDocument: true,
            Range: range);
        // 调整图片尺寸,可根据单元格大小自定义
        img.Width = width;
        img.Height = height;
    }
}

3. 修改导出逻辑新增图片插入

调整btn_export_Click方法,在文本替换完成后新增收集选中图片、插入到Word的逻辑,同时修复原代码中data1替换的语法错误:

private void btn_export_Click(object sender, EventArgs e)
{
    var text1 = textBox_2.Text;
    var text2 = textBox_2.Text;
    var text3 = textBox_3.Text;
    var text4 = textBox_4.Text;
    var data1 = dateTimePicker_1.Value.ToShortDateString();
    var data2 = dateTimePicker_2.Value.ToShortDateString();
    var text5 = textBox_5.Text;
    var text6 = textBox_6.Text;
    var text7 = comboBox_1.Text;
    var text8 = comboBox_2.Text;
    var text9 = comboBox_3.Text;
    var text10 = comboBox_4.Text;
    var text11 = textBox_7.Text;
    var text12 = textBox_8.Text;
    var text13 = comboBox_5.Text;
    var text14 = textBox_9.Text;            

    var wordApp = new Word.Application();
    wordApp.Visible = false;
    Word.Document wordDocument = null;
    try
    {
        wordDocument = wordApp.Documents.Open(TemplateFileName);

        // 替换文本占位符,修复原代码缺少逗号的语法错误
        ReplaceWordStub("{text1}", text1, wordDocument);
        ReplaceWordStub("{text2}", text2, wordDocument);
        ReplaceWordStub("{text3}", text3, wordDocument);
        ReplaceWordStub("{text4}", text4, wordDocument);
        ReplaceWordStub("{data1}", data1, wordDocument);
        ReplaceWordStub("{text5}", text5, wordDocument);
        ReplaceWordStub("{data2}", data2, wordDocument);
        ReplaceWordStub("{text6}", text6, wordDocument);
        ReplaceWordStub("{text7}", text7, wordDocument);
        ReplaceWordStub("{text8}", text8, wordDocument);
        ReplaceWordStub("{text9}", text9, wordDocument);
        ReplaceWordStub("{text10}", text10, wordDocument);
        ReplaceWordStub("{text11}", text11, wordDocument);
        ReplaceWordStub("{text12}", text12, wordDocument);
        ReplaceWordStub("{text13}", text13, wordDocument);
        ReplaceWordStub("{text14}", text14, wordDocument);

        // 收集选中的待导出图片路径
        List<string> exportImagePaths = new List<string>();
        string imgRootPath = @"D:\BASE\Images";
        foreach (Control ctrl in flowLayoutPanel_images.Controls)
        {
            if (ctrl is TableLayoutPanel panel)
            {
                foreach (Control subCtrl in panel.Controls)
                {
                    if (subCtrl is PictureBox pb)
                    {
                        string imgPath = Path.Combine(imgRootPath, pb.Name);
                        if (File.Exists(imgPath))
                        {
                            exportImagePaths.Add(imgPath);
                        }
                        break;
                    }
                }
                // 最多取3张图片
                if (exportImagePaths.Count >= 3) break;
            }
        }

        // 替换图片占位符
        if (exportImagePaths.Count >= 1) ReplaceStubWithImage("{Image1}", exportImagePaths[0], wordDocument);
        if (exportImagePaths.Count >= 2) ReplaceStubWithImage("{Image2}", exportImagePaths[1], wordDocument);
        if (exportImagePaths.Count >= 3) ReplaceStubWithImage("{Image3}", exportImagePaths[2], wordDocument);

        wordDocument.SaveAs2(@"D:\BASE\2.docx");
        wordApp.Visible = true;
    }
    catch (Exception ex)
    {
        MessageBox.Show("导出错误:" + ex.Message);
        // 出错时关闭Word进程避免残留
        wordDocument?.Close();
        wordApp.Quit();
    }
}

注意事项

  • 可根据Word表格单元格的实际尺寸,调整ReplaceStubWithImage方法中的width、height参数,避免图片溢出单元格
  • 如果不需要本地留存图片,也可以将动态生成的Image对象临时存为内存流再写入Word,无需本地存储,可根据实际需求调整逻辑

内容的提问来源于stack exchange,提问作者user17143191

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 08:06:04