请求编写Lua脚本:基于多分隔分类字段拆分复制表格记录
Lua脚本实现表格记录拆分并保证分类与编码一一对应
需求说明
编写Lua脚本拆分表格记录:当表格中Category Name(分类名称)和Cat Order code(分类编码)单元格存在逗号分隔的多条记录时,将其拆分为独立行,确保每条分类名称对应正确的分类编码。
示例数据
| Product Number | Category Name | Cat Order code |
|---|---|---|
| 1 | Category Name One,Category Name Two | 3,4 |
| 2 | Category Name Three, Category Name 4 | 2,1 |
期望结果
| Product Number | Category Name | Cat Order Code |
|---|---|---|
| 1 | Category Name One | 3 |
| 1 | Category Name Two | 4 |
| 2 | Category Name Three | 2 |
| 2 | Category Name Four | 1 |
现有问题
当前使用的Lua脚本仅能复制行拆分分类名称,但无法将Cat Order code的分隔值对应到正确的行中,代码如下:
for i = 1,records:size() do -- Get record i record = records:getrecord(i); -- Get the contents of the Category field categoryField = record:field("Category Name"):content(); -- Define a duplicates created counted n = 0; -- For each delimited value for k, v in string.gmatch(categoryField , "([^,]+)") do if (n == 0) then -- Remember the first value rememberMe = k; else -- For anything other than the first, duplicate the record newRecord = records:duplicaterecord(i); -- Define a unique key newRecord:field("Product number"):setcontent( newRecord:field("Product number"):content() .. "-" .. n); -- Set the new Category content newRecord:field("Category Name"):setcontent(k); end n = n + 1; end if n > 1 then -- If more than one duplicate was created, set the first value record:field("Category Name"):setcontent(rememberMe); end end
修正后的脚本
要解决分类与编码不对应的问题,需要同时拆分两个字段并按索引一一匹配,修正后的代码如下:
-- 从后往前遍历记录,避免新增记录干扰循环索引 for i = records:size(), 1, -1 do local record = records:getrecord(i) -- 获取两个字段的原始内容 local categoryStr = record:field("Category Name"):content() local catCodeStr = record:field("Cat Order code"):content() -- 拆分分类名称,去除前后空格 local categories = {} for cat in string.gmatch(categoryStr, "([^,]+)") do table.insert(categories, string.trim(cat)) end -- 拆分分类编码,去除前后空格 local catCodes = {} for code in string.gmatch(catCodeStr, "([^,]+)") do table.insert(catCodes, string.trim(code)) end -- 检查两个字段拆分后的数量是否一致,避免生成错误记录 if #categories ~= #catCodes then print("警告:记录" .. i .. "的分类名称与编码数量不匹配,跳过拆分") goto continue end -- 更新原记录为第一条拆分内容 record:field("Category Name"):setcontent(categories[1]) record:field("Cat Order code"):setcontent(catCodes[1]) -- 生成剩余的拆分记录 for idx = 2, #categories do local newRecord = records:duplicaterecord(i) -- 设置唯一产品编号 local productNum = newRecord:field("Product Number"):content() newRecord:field("Product Number"):setcontent(productNum .. "-" .. (idx - 1)) -- 匹配对应分类名称和编码 newRecord:field("Category Name"):setcontent(categories[idx]) newRecord:field("Cat Order code"):setcontent(catCodes[idx]) end ::continue:: end
关键改进点
- 双向字段拆分:同时处理分类名称和编码字段,确保两者拆分后数量匹配
- 索引严格对应:通过数组索引绑定分类与编码,保证对应关系准确
- 反向遍历:从最后一条记录往前处理,避免新增记录打乱循环顺序
- 空格清理:自动去除拆分后内容的前后空格,适配带空格的分隔格式
- 错误校验:添加数量不匹配的警告,避免生成无效记录
内容的提问来源于stack exchange,提问作者user2619963
相关产品推荐
相关产品推荐

