O uso da API do WPS Office permite automatizar a edição de documentos, especialmente na manipluação de tabelas, formatação de texto e gerenciamento de marcadores (bookmarks). Abaixo estão exemplos práticos de operações comuns.
Verificação e Acesso a Bookmarks
const doc = wps.WpsApplication().ActiveDocument;
const bookmarkRange = doc.Bookmarks.Item("nomeDoMarcador").Range;
Operações Básicas em Células de Tabela
- Acesso à célula:
table.Cell(linha, coluna)(índices começam em 1) - Definir texto:
table.Cell(1, 1).Range.Text = "Conteúdo"; - Obter texto:
const texto = table.Cell(1, 1).Range.Text; - Negrito:
table.Cell(1, 1).Range.Font.Bold = true;
Alinhamento de Texto
// Alinhamento horizontal
table.Cell(1, 1).Range.ParagraphFormat.Alignment = 0; // Esquerda
table.Range.ParagraphFormat.Alignment = 1; // Centralizado
// Alinhamento vertical (todas as células)
table.Range.Cells.VerticalAlignment = 1; // Centralizado verticalmente
Dimensões e Estrutura da Tabela
const totalLinhas = table.Rows.Count;
const totalColunas = table.Columns.Count;
// Adicionar linha após a segunda
table.Rows.Add(table.Rows.Item(2));
// Remover coluna (ex: última coluna)
table.Columns.Item(totalColunas).Delete();
// Mesclar células: da (1,2) até (3,4)
table.Cell(1, 2).Merge(table.Cell(3, 4));
Criação de Tabela em um Bookmark
const doc = wps.WpsApplication().ActiveDocument;
const refBookmark = doc.Bookmarks.Item("referencia");
const novoBookmark = doc.Bookmarks.Add("novaTabela", refBookmark.Range);
// Define o ponto de inserção logo após o bookmark de referência
novoBookmark.Start = refBookmark.End + 1;
const rangeInsercao = novoBookmark.Range;
// Cria tabela com 5 linhas e 4 colunas
const novaTabela = rangeInsercao.Tables.Add(rangeInsercao, 5, 4);
// Insere quebra de linha após a tabela
doc.Range(novoBookmark.End, novoBookmark.End).Select();
doc.ActiveWindow.Selection.TypeText('\r\n');
Formatação Visual da Tabela
// Largura das colunas
table.Columns.Item(1).Width = 35; // Primeira coluna
table.Columns.Item(2).Width = 115; // Segunda coluna
// Preenchimento interno (padding)
table.TopPadding = 2.8;
table.Cell(1, 1).TopPadding = 25;
table.Cell(1, 1).BottomPadding = 0;
// Bordas
table.Borders.InsideLineStyle = 1; // Linha interna contínua
// Configura bordas externas (superior, esquerda, inferior, direita)
for (let i = 1; i <= 4; i++) {
const borda = table.Borders.Item(i);
borda.LineStyle = 1; // Contínua
borda.LineWidth = 4; // Espessura
borda.Color = 0; // Preto
}
// Remover borda superior da primeira célula
table.Cell(1, 1).Borders.Item(1).LineStyle = 0;
// Remover bordas inferior e esquerda da última linha, coluna i
table.Cell(table.Rows.Count, i).Borders.OutsideLineStyle = 0;
Remoção de Recuo de Parágrafo
range.ParagraphFormat.CharacterUnitFirstLineIndent = 0;
range.ParagraphFormat.FirstLineIndent = 0;
range.ParagraphFormat.LeftIndent = 0;
range.ParagraphFormat.CharacterUnitLeftIndent = 0;
Posicionamento no Documento
const marcador = doc.Bookmarks.Item('projectNum');
doc.Range(marcador.Start, marcador.Start).Select();
Estilização de Fonte
table.Range.Font.NameAscii = '宋体';
table.Range.Font.NameFarEast = '宋体';
table.Range.Font.Size = 12;
Exemplo Completo: Preenchimento Dinâmico de Tabela
Dado um array bidimensional com cabeçalhos, unidades e valores anuais, a função abaixo reestrutura uma tabela existente em um bookmark:
function fundingArrangement(dados, nomeMarcador) {
const doc = wps.WpsApplication().ActiveDocument;
const bookmark = doc.Bookmarks.Item(nomeMarcador);
if (!bookmark || bookmark.Empty) return;
let tabela = bookmark.Range.Tables.Item(1);
const cabecalho = dados[0]; // Ex: ["Ano", "2021", ..., "Nota"]
const unidades = dados[1]; // Ex: ["Empresa A", "Empresa B"]
const registros = dados.slice(2);
// Limpa conteúdo existente (mantém cabeçalho)
while (tabela.Rows.Count > 1) tabela.Rows.Item(2).Delete();
while (tabela.Columns.Count > 2) tabela.Columns.Item(tabela.Columns.Count).Delete();
// Adiciona linhas para cada unidade
for (let i = 0; i < unidades.length; i++) {
tabela.Rows.Add(tabela.Rows.Item(2));
tabela.Cell(i + 2, 1).Range.Text = i + 1;
tabela.Cell(i + 2, 2).Range.Text = unidades[i];
}
// Adiciona colunas para cada ano + nota
for (let j = 0; j < cabecalho.length; j++) {
tabela.Columns.Add(tabela.Columns.Item(3));
tabela.Cell(1, j + 3).Range.Text = cabecalho[j];
}
// Preenche valores
registros.forEach(reg => {
const ano = reg[0];
const unidade = reg[1];
const valor = reg[2];
const observacao = reg[4];
const idxLinha = unidades.indexOf(unidade) + 2;
const idxColuna = cabecalho.indexOf(ano) + 3;
if (idxLinha > 1 && idxColuna > 2) {
tabela.Cell(idxLinha, idxColuna).Range.Text = parseFloat(valor);
}
if (observacao) {
tabela.Cell(idxLinha, cabecalho.length + 2).Range.Text = observacao;
}
});
// Calcula totais por coluna
const ultimaLinha = tabela.Rows.Count + 1;
tabela.Rows.Add(tabela.Rows.Item(ultimaLinha));
tabela.Cell(ultimaLinha, 1).Range.Text = 'Total';
tabela.Cell(ultimaLinha, 1).Merge(tabela.Cell(ultimaLinha, 2));
for (let c = 3; c <= tabela.Columns.Count; c++) {
let soma = 0;
for (let r = 2; r < ultimaLinha; r++) {
const val = parseFloat(tabela.Cell(r, c).Range.Text) || 0;
soma += val;
}
if (soma > 0) {
tabela.Cell(ultimaLinha, c).Range.Text = soma.toFixed(2);
}
}
// Ajusta larguras
tabela.Columns.Item(1).Width = 35;
tabela.Columns.Item(2).Width = 115;
for (let i = 3; i <= tabela.Columns.Count - 1; i++) {
tabela.Columns.Item(i).Width = 65;
}
tabela.Columns.Item(tabela.Columns.Count).Width = 75;
}