WPS Writer JS API Core Reference
Code Execution Environment
- Code passes through
new Function(code)() executed synchronously in WPS Plugin Host
- Globally available objects:
Application, wps
- Must use
var to declare variables (let/const/arrow functions are not supported)
- The last line must return a result string
Common Objects
Application.ActiveDocument // 当前文档 (Document)
Application.Selection // 当前选区 (Selection)
Document.Content // 全文 Range
Document.Paragraphs // 段落集合 Paragraphs
Document.Tables // 表格集合 Tables
Document.Sections // 节集合 Sections
Document.Bookmarks // 书签集合
Selection Operations
Selection.Text // 读取/设置选区文本
Selection.TypeText(text) // 在光标处输入(替换选区)
Selection.InsertAfter(text) // 在选区后插入
Selection.InsertBefore(text) // 在选区前插入
Selection.MoveDown(unit, count) // 下移光标
Selection.MoveRight(unit, count) // 右移光标
Selection.Collapse(direction) // 收缩选区 (0=wdCollapseEnd, 1=wdCollapseStart)
Selection.WholeStory() // 选中全文
Selection.HomeKey(unit) // 移动到文档/行首
Selection.EndKey(unit) // 移动到文档/行尾
Range Operations
Range.Text // 读取/设置文本
Range.InsertAfter(text) // 在范围后插入
Range.InsertBefore(text) // 在范围前插入
Range.Start / Range.End // 起止字符位置
Range.Select() // 将此范围设为选区
Range.Delete() // 删除范围内容
Formatting
Range.Font.Name = "微软雅黑"
Range.Font.Size = 14
Range.Font.Bold = true / false
Range.Font.Italic = true / false
Range.Font.Color = 0xFF0000 // BGR 颜色
Range.Font.Underline = 1 // wdUnderlineSingle
Range.ParagraphFormat.Alignment = 1 // 0=左, 1=居中, 2=右, 3=两端
Range.ParagraphFormat.LineSpacing = 24 // 行距 (磅)
Range.ParagraphFormat.SpaceBefore = 6
Range.ParagraphFormat.SpaceAfter = 6
Range.ParagraphFormat.FirstLineIndent = 24 // 首行缩进
Range.Style = "标题 1" // 设置样式
Table Operations
Document.Tables.Add(range, rows, cols)
Table.Cell(row, col).Range.Text = "文本"
Table.Rows.Add()
Table.Columns.Add()
Table.Cell(row, col).Merge(Table.Cell(row, col2))
Safety Standards
- Always check whether the object exists before operating:
if (!doc) return "无活动文档";
- Wrap large-scale operations in try/catch
- Do not assume the document contains specific content; check before operating
- Before replacing the selection, confirm that Selection.Text is not empty