📔 金山办公产品帮助中心

WPS文字插入表格速度优化案例

文档由 任财应 于 2022-09-27 23:15 创建,由 任财应 于 2022-09-27 23:15 更新
文档标签:
文档分类:
21

案例需求:

大量数据生成表格时,优化其速度

代码流程

将遍历表格的方式改为先插入数据,再对此部分数据使用 ConvertToTable “转换为表格” 功能

代码实现

//大量数据生成表格时

var app = wps.WpsApplication()
var doc = wps.WpsApplication().ActiveDocument
var selection = app.Selection

//新方法,避免大量操作表格
function newCreateTable(row, col, separator) {
    console.time("Insert Table New Macro");
    let TabText = ""
    for (let i = 1; i <= row; i++) {
        for (let j = 1; j <= col; j++) {
            TabText += `${i},${j}${separator}`
        }
        TabText = TabText.substring(0, TabText.length - 1)
        TabText += "\r\n"
    }
    // console.log("表格文本", TabText)

    let beforeStart, nowEnd;
    beforeStart = selection.Range.Start;
    selection.TypeText(TabText) //输入表格文本
    nowEnd = selection.Range.End;
    selection.SetRange(beforeStart, nowEnd)
    selection.Range.ConvertToTable(separator)  //转换为表格

    console.timeEnd("Insert Table New Macro");
}

//老方法,循环每次都要操作表格
function oldCreateTable(row, col) {
    console.time("Insert Table Old Macro");

    let tab = doc.Tables.Add(selection.Range, $NumRows = row, $NumColumns = col)
    window.t = tab
    let borders = tab.Borders;
    borders.InsideLineStyle = 1;
    borders.OutsideLineStyle = 1;

    for (let i = 1; i <= row; i++) {
        for (let j = 1; j <= col; j++) {
            tab.Cell(i, j).Range.Text = `${i},${j}`
        }
    }
    console.timeEnd("Insert Table Old Macro");
}

//测试调用
function test(row, col) {
    selection.TypeText("老方法插入表格\r\n")
    oldCreateTable(row, col)
    selection.WholeStory()
    selection.EndKey()
    selection.TypeParagraph()
    selection.TypeText("新方法插入表格\r\n")
    newCreateTable(row, col, "|")
    selection.WholeStory()
    selection.EndKey()
}

test(500, 5) //开始测试,生成500行5列测试数据

// 测试结果 :新方法1秒,老方法36秒
// VM1586:45 Insert Table Old Macro: 36092.065185546875 ms
// VM1586:27 Insert Table New Macro: 1180.81494140625 ms