wordVSTO插件实现自动填充序号

wordVSTO插件实现自动填充序号

开发环境:VS2022

核心代码如下:

python 复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using Word = Microsoft.Office.Interop.Word;
using Office = Microsoft.Office.Core;
using Microsoft.Office.Tools.Word;

namespace WordAddIn1
{
    public partial class ThisAddIn
    {
        private void ThisAddIn_Startup(object sender, System.EventArgs e)
        {
        }

        private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
        {
        }

        protected override Microsoft.Office.Core.IRibbonExtensibility CreateRibbonExtensibilityObject()
        {
            return new 鑫鑫Ribbon();
        }

        #region VSTO 生成的代码

        /// <summary>
        /// 设计器支持所需的方法 - 不要修改
        /// 使用代码编辑器修改此方法的内容。
        /// </summary>
        private void InternalStartup()
        {
            this.Startup += new System.EventHandler(ThisAddIn_Startup);
            this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
        }
        
        #endregion
    }

    [ComVisible(true)]
    [Guid("A1B2C3D4-E5F6-7890-ABCD-EF1234567890")]
    public class 鑫鑫Ribbon : Office.IRibbonExtensibility
    {
        private Office.IRibbonUI ribbon;

        public string GetCustomUI(string ribbonID)
        {
            // 确保返回有效的Ribbon XML
            string ribbonXml = @"<customUI xmlns='http://schemas.microsoft.com/office/2009/07/customui' onLoad='OnLoad'>
    <ribbon>
        <tabs>
            <tab id='XinXinTab' label='鑫鑫工具箱' insertAfterMso='TabHome'>
                <group id='XinXinGroup' label='表格工具'>
                    <button id='btnFillNumbers' 
                            label='自动填充序号' 
                            size='large'
                            onAction='OnFillNumbersClick'
                            imageMso='Numbering'/>
                </group>
            </tab>
        </tabs>
    </ribbon>
</customUI>";
            
            // 记录日志以便调试
            try
            {
                System.IO.File.WriteAllText(System.IO.Path.Combine(System.IO.Path.GetTempPath(), "RibbonDebug.log"), 
                    $"Ribbon XML generated at {DateTime.Now}: {ribbonXml}");
            }
            catch { }
            
            return ribbonXml;
        }

        public void OnFillNumbersClick(Office.IRibbonControl control)
        {
            try
            {
                Word.Application wordApp = Globals.ThisAddIn.Application;
                Word.Selection selection = wordApp.Selection;
                
                // 检查是否选中了表格
                if (selection.Range.Tables.Count > 0)
                {
                    Word.Table selectedTable = selection.Range.Tables[1];
                    FillTableWithNumbers(selectedTable);
                    MessageBox.Show($"已为选中的表格填充序号,共 {selectedTable.Rows.Count} 行", "成功", 
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    // 如果没有选中表格,检查文档中的所有表格
                    Word.Document doc = wordApp.ActiveDocument;
                    if (doc.Tables.Count > 0)
                    {
                        int totalTables = 0;
                        foreach (Word.Table table in doc.Tables)
                        {
                            FillTableWithNumbers(table);
                            totalTables++;
                        }
                        MessageBox.Show($"已为文档中的 {totalTables} 个表格填充序号", "成功", 
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        MessageBox.Show("文档中没有找到表格!", "提示", 
                            MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"填充序号时出错: {ex.Message}", "错误", 
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void FillTableWithNumbers(Word.Table table)
        {
            for (int i = 1; i <= table.Rows.Count; i++)
            {
                try
                {
                    table.Cell(i, 1).Range.Text = i.ToString();
                }
                catch
                {
                    // 如果第一列不存在或无法访问,跳过该行
                }
            }
        }

        public void OnLoad(Office.IRibbonUI ribbonUI)
        {
            this.ribbon = ribbonUI;
            try
            {
                System.IO.File.AppendAllText(System.IO.Path.Combine(System.IO.Path.GetTempPath(), "RibbonDebug.log"), 
                    $"Ribbon loaded at {DateTime.Now}\r\n");
            }
            catch { }
        }
    }
}

工程源码文件:https://download.csdn.net/download/weixin_43050480/91997447

相关推荐
SmartRadio6 小时前
CH585M+MK8000、DW1000 (UWB)+W25Q16的低功耗室内定位设计
c语言·开发语言·uwb
kylezhao20196 小时前
C#winform数据绑定
c#
rfidunion6 小时前
QT5.7.0编译移植
开发语言·qt
rit84324997 小时前
MATLAB对组合巴克码抗干扰仿真的实现方案
开发语言·matlab
大、男人7 小时前
python之asynccontextmanager学习
开发语言·python·学习
hqwest7 小时前
码上通QT实战08--导航按钮切换界面
开发语言·qt·slot·信号与槽·connect·signals·emit
AC赳赳老秦8 小时前
DeepSeek 私有化部署避坑指南:敏感数据本地化处理与合规性检测详解
大数据·开发语言·数据库·人工智能·自动化·php·deepseek
不知道累,只知道类8 小时前
深入理解 Java 虚拟线程 (Project Loom)
java·开发语言
国强_dev8 小时前
Python 的“非直接原因”报错
开发语言·python
YMatrix 官方技术社区8 小时前
YMatrix 存储引擎解密:MARS3 存储引擎如何超越传统行存、列存实现“时序+分析“场景性能大幅提升?
开发语言·数据库·时序数据库·数据库架构·智慧工厂·存储引擎·ymatrix