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

如何用Office.JS API获取Word所有自定义及预定义样式相关信息

实现方案

1. 列出所有用户自定义样式并获取类型

直接遍历文档的styles集合,通过builtIn属性判断是否为用户自定义样式,通过type属性获取样式类型。
示例代码如下:

await Word.run(async (context) => {
  // 加载样式集合的必要属性
  const allStyles = context.document.styles;
  allStyles.load("items/name, items/builtIn, items/type");
  await context.sync();

  // 过滤出非内置的用户自定义样式
  const customStyles = allStyles.items.filter(style => !style.builtIn);
  customStyles.forEach(style => {
    console.log(`样式名:${style.name},样式类型:${style.type}`);
  });
});

style.type返回的是Word.StyleType枚举值,常用取值对应样式类型如下:

  • paragraph:段落样式
  • character:字符样式
  • table:表格样式
  • list:列表样式

2. 获取内置样式的本地化名称与对应类型

你之前找到的Word.Style枚举是内置样式的通用固定标识,不受语言环境影响,要获取本地化名称直接读取样式的nameLocal属性即可,该属性会自动返回当前Office语言环境下的样式名称。
示例代码如下:

await Word.run(async (context) => {
  const allStyles = context.document.styles;
  // 额外加载nameLocal属性获取本地化名称
  allStyles.load("items/name, items/nameLocal, items/builtIn, items/type");
  await context.sync();

  // 过滤出内置样式
  const builtInStyles = allStyles.items.filter(style => style.builtIn);
  builtInStyles.forEach(style => {
    console.log(`通用标识:${style.name},本地化名称:${style.nameLocal},样式类型:${style.type}`);
  });
});

相关属性说明:

  • name:内置样式的固定英文标识,和Word.Style枚举值一一对应,不会随Office语言变化
  • nameLocal:内置样式的本地化名称,适配当前Office界面语言,中文环境下会返回「标题 1」「正文」「网格表」这类中文名称

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 07:06:04