LUA 对象转excel
1. 首先把LUA 转成JSON 对象
因为是excel, 所以第一层要是数组,否则没有什么意义,即lua对象要是一个数组比较合理。这里使用开源的json.lua, 但是开源的,对于数字作下标的,或者是一个数组里,不同类型的key混合的情况无法转换,所以我进行了一定的改进,先进行了扫描判断是不是混合的key,是的话,取消key,把key到结构里作为一个字段处理。源码如下:
local json = loadfile("json.lua/json.lua")()
t1 = new Test();
print(json.encode(t1))
库代码:
--
-- json.lua
--
-- Copyright (c) 2020 rxi
--
-- Permission is hereby granted, free of charge, to any person obtaining a copy of
-- this software and associated documentation files (the "Software"), to deal in
-- the Software without restriction, including without limitation the rights to
-- use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
-- of the Software, and to permit persons to whom the Software is furnished to do
-- so, subject to the following conditions:
--
-- The above copyright notice and this permission notice shall be included in all
-- copies or substantial portions of the Software.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-- SOFTWARE.
--local json = { _version = "0.1.2" }-------------------------------------------------------------------------------
-- Encode
-------------------------------------------------------------------------------local encodelocal escape_char_map = {[ "\\" ] = "\\",[ "\"" ] = "\"",[ "\b" ] = "b",[ "\f" ] = "f",[ "\n" ] = "n",[ "\r" ] = "r",[ "\t" ] = "t",
}local escape_char_map_inv = { [ "/" ] = "/" }
for k, v in pairs(escape_char_map) doescape_char_map_inv[v] = k
endlocal function escape_char(c)return "\\" .. (escape_char_map[c] or string.format("u%04x", c:byte()))
endlocal function encode_nil(val)return "null"
endlocal function encode_table(val, stack)local res = {}local mixedKeyType =falselocal tmpobj={}stack = stack or {}-- Circular reference?if stack[val] then error("circular reference") endstack[val] = trueif rawget(val, 1) ~= nil or next(val) == nil then-- Treat as array -- check keys are valid and it is not sparselocal n = 0for k in pairs(val) doif type(k) ~= "number" then--error("invalid table: mixed or invalid key types")mixedKeyType=true;endn = n + 1end-- if n ~= #val then-- error("invalid table: sparse array")-- end-- Encodefor i, v in ipairs(val) doif mixedKeyType then if type(v) == "table" thenrawset(v, "vv__objid",tostring(k))elsetmpobj={}tmpobj.k = i;tmpobj.v = v;v = tmpobj;endendtable.insert(res, encode(v, stack))endstack[val] = nilreturn "[" .. table.concat(res, ",") .. "]"else-- Treat as an objectfor k, v in pairs(val) doif type(k) ~= "string" then-- error("invalid table: mixed or invalid key types : "..type(k) .. "value:"..tostring(k))mixedKeyType = true;break;endendfor k, v in pairs(val) doif mixedKeyType thenif type(v) == "table" thenrawset(v, "vv__objid",tostring(k))elsetmpobj={}tmpobj.k = k;tmpobj.v = v;v = tmpobj;endtable.insert(res, encode(v, stack))elsetable.insert(res, encode(k, stack) .. ":" .. encode(v, stack))endendstack[val] = nilif mixedKeyType thenreturn "[" .. table.concat(res, ",\n") .. "]"elsereturn "{" .. table.concat(res, ",") .. "}"endend
endlocal function encode_string(val)return '"' .. val:gsub('[%z\1-\31\\"]', escape_char) .. '"'
endlocal function encode_number(val)-- Check for NaN, -inf and infif val ~= val or val <= -math.huge or val >= math.huge thenerror("unexpected number value '" .. tostring(val) .. "'")endreturn string.format("%.14g", val)
endlocal type_func_map = {[ "nil" ] = encode_nil,[ "table" ] = encode_table,[ "string" ] = encode_string,[ "number" ] = encode_number,[ "boolean" ] = tostring,
}encode = function(val, stack)local t = type(val)local f = type_func_map[t]if f thenreturn f(val, stack)enderror("unexpected type '" .. t .. "'")
endfunction json.encode(val)return ( encode(val) )
end-------------------------------------------------------------------------------
-- Decode
-------------------------------------------------------------------------------local parselocal function create_set(...)local res = {}for i = 1, select("#", ...) dores[ select(i, ...) ] = trueendreturn res
endlocal space_chars = create_set(" ", "\t", "\r", "\n")
local delim_chars = create_set(" ", "\t", "\r", "\n", "]", "}", ",")
local escape_chars = create_set("\\", "/", '"', "b", "f", "n", "r", "t", "u")
local literals = create_set("true", "false", "null")local literal_map = {[ "true" ] = true,[ "false" ] = false,[ "null" ] = nil,
}local function next_char(str, idx, set, negate)for i = idx, #str doif set[str:sub(i, i)] ~= negate thenreturn iendendreturn #str + 1
endlocal function decode_error(str, idx, msg)local line_count = 1local col_count = 1for i = 1, idx - 1 docol_count = col_count + 1if str:sub(i, i) == "\n" thenline_count = line_count + 1col_count = 1endenderror( string.format("%s at line %d col %d", msg, line_count, col_count) )
endlocal function codepoint_to_utf8(n)-- http://scripts.sil.org/cms/scripts/page.php?site_id=nrsi&id=iws-appendixalocal f = math.floorif n <= 0x7f thenreturn string.char(n)elseif n <= 0x7ff thenreturn string.char(f(n / 64) + 192, n % 64 + 128)elseif n <= 0xffff thenreturn string.char(f(n / 4096) + 224, f(n % 4096 / 64) + 128, n % 64 + 128)elseif n <= 0x10ffff thenreturn string.char(f(n / 262144) + 240, f(n % 262144 / 4096) + 128,f(n % 4096 / 64) + 128, n % 64 + 128)enderror( string.format("invalid unicode codepoint '%x'", n) )
endlocal function parse_unicode_escape(s)local n1 = tonumber( s:sub(1, 4), 16 )local n2 = tonumber( s:sub(7, 10), 16 )-- Surrogate pair?if n2 thenreturn codepoint_to_utf8((n1 - 0xd800) * 0x400 + (n2 - 0xdc00) + 0x10000)elsereturn codepoint_to_utf8(n1)end
endlocal function parse_string(str, i)local res = ""local j = i + 1local k = jwhile j <= #str dolocal x = str:byte(j)if x < 32 thendecode_error(str, j, "control character in string")elseif x == 92 then -- `\`: Escaperes = res .. str:sub(k, j - 1)j = j + 1local c = str:sub(j, j)if c == "u" thenlocal hex = str:match("^[dD][89aAbB]%x%x\\u%x%x%x%x", j + 1)or str:match("^%x%x%x%x", j + 1)or decode_error(str, j - 1, "invalid unicode escape in string")res = res .. parse_unicode_escape(hex)j = j + #hexelseif not escape_chars[c] thendecode_error(str, j - 1, "invalid escape char '" .. c .. "' in string")endres = res .. escape_char_map_inv[c]endk = j + 1elseif x == 34 then -- `"`: End of stringres = res .. str:sub(k, j - 1)return res, j + 1endj = j + 1enddecode_error(str, i, "expected closing quote for string")
endlocal function parse_number(str, i)local x = next_char(str, i, delim_chars)local s = str:sub(i, x - 1)local n = tonumber(s)if not n thendecode_error(str, i, "invalid number '" .. s .. "'")endreturn n, x
endlocal function parse_literal(str, i)local x = next_char(str, i, delim_chars)local word = str:sub(i, x - 1)if not literals[word] thendecode_error(str, i, "invalid literal '" .. word .. "'")endreturn literal_map[word], x
endlocal function parse_array(str, i)local res = {}local n = 1i = i + 1while 1 dolocal xi = next_char(str, i, space_chars, true)-- Empty / end of array?if str:sub(i, i) == "]" theni = i + 1breakend-- Read tokenx, i = parse(str, i)res[n] = xn = n + 1-- Next tokeni = next_char(str, i, space_chars, true)local chr = str:sub(i, i)i = i + 1if chr == "]" then break endif chr ~= "," then decode_error(str, i, "expected ']' or ','") endendreturn res, i
endlocal function parse_object(str, i)local res = {}i = i + 1while 1 dolocal key, vali = next_char(str, i, space_chars, true)-- Empty / end of object?if str:sub(i, i) == "}" theni = i + 1breakend-- Read keyif str:sub(i, i) ~= '"' thendecode_error(str, i, "expected string for key")endkey, i = parse(str, i)-- Read ':' delimiteri = next_char(str, i, space_chars, true)if str:sub(i, i) ~= ":" thendecode_error(str, i, "expected ':' after key")endi = next_char(str, i + 1, space_chars, true)-- Read valueval, i = parse(str, i)-- Setres[key] = val-- Next tokeni = next_char(str, i, space_chars, true)local chr = str:sub(i, i)i = i + 1if chr == "}" then break endif chr ~= "," then decode_error(str, i, "expected '}' or ','") endendreturn res, i
endlocal char_func_map = {[ '"' ] = parse_string,[ "0" ] = parse_number,[ "1" ] = parse_number,[ "2" ] = parse_number,[ "3" ] = parse_number,[ "4" ] = parse_number,[ "5" ] = parse_number,[ "6" ] = parse_number,[ "7" ] = parse_number,[ "8" ] = parse_number,[ "9" ] = parse_number,[ "-" ] = parse_number,[ "t" ] = parse_literal,[ "f" ] = parse_literal,[ "n" ] = parse_literal,[ "[" ] = parse_array,[ "{" ] = parse_object,
}parse = function(str, idx)local chr = str:sub(idx, idx)local f = char_func_map[chr]if f thenreturn f(str, idx)enddecode_error(str, idx, "unexpected character '" .. chr .. "'")
endfunction json.decode(str)if type(str) ~= "string" thenerror("expected argument of type string, got " .. type(str))endlocal res, idx = parse(str, next_char(str, 1, space_chars, true))idx = next_char(str, idx, space_chars, true)if idx <= #str thendecode_error(str, idx, "trailing garbage")endreturn res
endreturn json
二、把JSON转成CSV
使用python,json_to_csv这个库 。 它会把树形展平
import sys
import json
import csv
import io##
# Convert to string keeping encoding in mind...
##
def to_string(s):try:return str(s)except:#Change the encoding type if neededreturn s.encode('utf-8')##
# This function converts an item like
# {
# "item_1":"value_11",
# "item_2":"value_12",
# "item_3":"value_13",
# "item_4":["sub_value_14", "sub_value_15"],
# "item_5":{
# "sub_item_1":"sub_item_value_11",
# "sub_item_2":["sub_item_value_12", "sub_item_value_13"]
# }
# }
# To
# {
# "node_item_1":"value_11",
# "node_item_2":"value_12",
# "node_item_3":"value_13",
# "node_item_4_0":"sub_value_14",
# "node_item_4_1":"sub_value_15",
# "node_item_5_sub_item_1":"sub_item_value_11",
# "node_item_5_sub_item_2_0":"sub_item_value_12",
# "node_item_5_sub_item_2_0":"sub_item_value_13"
# }
##
def reduce_item(key, value):global reduced_item#Reduction Condition 1if type(value) is list:i=0for sub_item in value:reduce_item(key+'_'+to_string(i), sub_item)i=i+1#Reduction Condition 2elif type(value) is dict:sub_keys = value.keys()for sub_key in sub_keys:reduce_item(key+'_'+to_string(sub_key), value[sub_key])#Base Conditionelse:reduced_item[to_string(key)] = to_string(value)if __name__ == "__main__":if len(sys.argv) != 4:print ("\nUsage: python json_to_csv.py <node> <json_in_file_path> <csv_out_file_path>\n")else:#Reading argumentsnode = sys.argv[1]json_file_path = sys.argv[2]csv_file_path = sys.argv[3]with io.open(json_file_path, 'r', encoding='utf-8-sig') as fp:json_value = fp.read()raw_data = json.loads(json_value)try:data_to_be_processed = raw_data[node]except:data_to_be_processed = raw_dataprocessed_data = []header = []for item in data_to_be_processed:reduced_item = {}reduce_item(node, item)header += reduced_item.keys()processed_data.append(reduced_item)header = list(set(header))header.sort()with open(csv_file_path, 'w+') as f:writer = csv.DictWriter(f, header, quoting=csv.QUOTE_ALL)writer.writeheader()for row in processed_data:writer.writerow(row)print ("Just completed writing csv file with %d columns" % len(header))
三、把csv转成xlsx文件
使用开源的xlsxwriter, pip先安装一下, 使用代码如下:
import sys
import json
import csv
import io
from xlsxwriter.workbook import Workbookif __name__ == "__main__":if len(sys.argv) != 3:print ("\nUsage: python csv_to_xlsx.py <csv_file> <xlsx_file>\n")else:#Reading argumentscsvfile = sys.argv[1]xlsxfile = sys.argv[2]workbook = Workbook(xlsxfile)worksheet = workbook.add_worksheet()f= open(csvfile, 'rt', encoding='utf8')reader = csv.reader(f)for r, row in enumerate(reader):for c, col in enumerate(row):worksheet.write(r, c, col)workbook.close()f.close()
三步走完,完成lua转excel的工作。
相关文章:
LUA 对象转excel
1. 首先把LUA 转成JSON 对象 因为是excel, 所以第一层要是数组,否则没有什么意义,即lua对象要是一个数组比较合理。这里使用开源的json.lua, 但是开源的,对于数字作下标的,或者是一个数组里,不同类型的key…...

深入理解 Flink(八)Flink Task 部署初始化和启动详解
JobMaster 部署 Task 核心入口: JobMaster.onStart();部署 Task 链条:JobMaster --> DefaultScheduler --> SchedulingStrategy --> ExecutionVertex --> Execution --> RPC请求 --> TaskExecutor TaskExecutor 处理 JobMaster 的 …...
openssl3.2 - 官方demo学习 - pkey - EVP_PKEY_DSA_paramfromdata.c
文章目录 openssl3.2 - 官方demo学习 - pkey - EVP_PKEY_DSA_paramfromdata.c概述笔记END openssl3.2 - 官方demo学习 - pkey - EVP_PKEY_DSA_paramfromdata.c 概述 开源工程包含的头文件类型是.inc, 要重命名为.h, 否则没有c头文件语法提示 从数组中载入大数p,q,g 建立ossl…...

【k8s】Kubernetes技术和相关命令简介
一、 Kubernetes简介 Kubernetes是Google开源的一个容器编排引擎,它支持自动化部署、大规模可伸缩、应用容器化管理。在生产环境中部署一个应用程序时,通常要部署该应用的多个实例以便对应用请求进行负载均衡。kubernetes,简称K8s࿰…...

清晰光谱空间:全自动可调波长系统的高光谱成像优势
高光谱成像技术 高光谱成像技术是一种捕获和分析宽波长信息的技术,能够对材料和特征进行详细的光谱分析和识别。高光谱成像技术的实现通过高光谱相机,其工作原理是使用多个光学传感器或光学滤波器分离不同波长的光,并捕获每个波段的图像&…...

23.实战演练--个人主页
<?xml version"1.0" encoding"utf-8"?> <manifest xmlns:android"http://schemas.android.com/apk/res/android"xmlns:tools"http://schemas.android.com/tools"><applicationandroid:allowBackup"true"an…...

[剪藏] - 任泽平年终演讲精华:点燃希望——2024中国经济十大预测
任泽平年终演讲精华:点燃希望——2024中国经济十大预测 泽平宏观 2023-12-23 08:01 发表于上海 12月22日22:30,任泽平年终秀“点燃希望乐观者前行——2024中国经济十大预测”圆满收官。 泽平宏观、北京广播电视台、上海高净值研究院、北京时间等携手打…...

基于LabVIEW的压力传感器测试系统
摘要 现在各类压力传感器已广泛应用于各种工业自控环境,对压力传感器的研究 及应用,既可以体现一个国家的科技发展水平,又可以提升国家的综合国力,还 可以在丰富、方便和智能化人们的生活方面做出重要的贡献。而针对不同仪器组 成…...
Vue 如何使用WebSocket与服务器建立链接 持续保持通信
WebSocket 浏览器通过JavaScript向服务器发出建立WebSocket链接的请求,链接建立后,客户端和服务器端就可以通过TCP链接直接交互数据。WebSocket链接后可以通过send()方法来向服务器发送数据,并通过onnessage事件来接受服务器返回的数据。 创…...
自动驾驶模拟器
目录 Carla 自动驾驶模拟器 Udacity自动驾驶模拟器 Carla 自动驾驶模拟器 pip install carla 需要下载地图 Udacity自动驾驶模拟器...

Jmeter的文件参数化:CSV数据文件设置和_CSVRead函数
一、CSV数据文件设置 1、简介 CSV数据文件配置(CSV Data Set Config)可以将CSV文件中数据读入自定义变量中 Jmeter中CSV数据文件配置的界面如下图所示: 其中: (1)文件编码 文件的编码格式,与所…...

windows编译TensorFlowServing
概述 整个编译打包过程的总体思路,是参照在linux下的编译流程,配置环境,执行编译命令,根据编译器/链接器反馈的错误,修改相应的源码或者相关库文件的存放路径,编译出windows平台下静态库和二进制执行文件。…...
debian 12 安装 浏览器 Epiphany
Epiphany 什么epiphany-browser epiphany-browser 是: Epiphany 是一款简单而强大的 GNOME 网络浏览器,针对 非技术用户。它的原则是简单和标准 合规。 简单性是通过精心设计的用户界面和依赖来实现的 在用于执行外部任务(如阅读 电子邮件…...

Kafka-消费者-KafkaConsumer分析
与KafkaProducer不同的是,KafkaConsumer不是一个线程安全的类。 为了便于分析,我们认为下面介绍的所有操作都是在同一线程中完成的,所以不需要考虑锁的问题。 这种设计将实现多线程处理消息的逻辑转移到了调用KafkaConsumer的代码中&#x…...

Spring | Spring中的Bean--下
Spring中的Bean: 4.Bean的生命周期5.Bean的配装配式 ( 添加Bean到IOC容器的方式 依赖注入的方式 )5.1 基于XML的配置5.2 基于Annotation (注解) 的装配 (更常用)5.3 自动装配 4.Bean的生命周期 Spring容器可以管理 singleton作用域的Bean的生命周期,在此…...

本周五上海见 第二届证券基金行业先进计算技术大会暨2024低时延技术创新实践论坛(上海站)即将召开
低时延技术是证券基金期货领域业务系统的核心技术,是打造极速交易系统领先优势的关键,也是证券基金行业关注的前沿技术热点。 1月19日下午,第二届证券基金行业先进计算技术大会暨2024低时延技术创新实践论坛(上海站)即…...

怎么安装IK分词器
.安装IK分词器 1.在线安装ik插件(较慢) # 进入容器内部 docker exec -it elasticsearch /bin/bash # 在线下载并安装 ./bin/elasticsearch-plugin install https://github.com/medcl/elasticsearch-analysis-ik/releases/download/v7.12.1/elastics…...

【踩坑】flask_uploads报错cannot import name ‘secure_filename‘
转载请注明出处:小锋学长生活大爆炸[xfxuezhang.cn] 背景说明 截至目前,用新版的flask实现文件上传(用到flask_uploads库),会出现这个问题。 问题原因 版本问题,新的werkzeug已经把secure_filename的位置改了。 解决方法 手动修改…...

AI编程可视化Java项目拆解第一弹,解析本地Java项目
之前分享过一篇使用 AI 可视化 Java 项目的文章,同步在 AI 破局星球、知乎、掘金等地方都分享了。 原文在这里AI 编程:可视化 Java 项目 有很多人感兴趣,我打算写一个系列文章拆解这个项目,大家多多点赞支持~ 今天分享的是第一…...

使用arcgis pro是类似的控件样式 WPF
1.资源加载 <controls:ProWindow.Resources><ResourceDictionary><ResourceDictionary.MergedDictionaries><extensions:DesignOnlyResourceDictionary Source"pack://application:,,,/ArcGIS.Desktop.Framework;component\Themes\Default.xaml&quo…...

大话软工笔记—需求分析概述
需求分析,就是要对需求调研收集到的资料信息逐个地进行拆分、研究,从大量的不确定“需求”中确定出哪些需求最终要转换为确定的“功能需求”。 需求分析的作用非常重要,后续设计的依据主要来自于需求分析的成果,包括: 项目的目的…...
day52 ResNet18 CBAM
在深度学习的旅程中,我们不断探索如何提升模型的性能。今天,我将分享我在 ResNet18 模型中插入 CBAM(Convolutional Block Attention Module)模块,并采用分阶段微调策略的实践过程。通过这个过程,我不仅提升…...

python/java环境配置
环境变量放一起 python: 1.首先下载Python Python下载地址:Download Python | Python.org downloads ---windows -- 64 2.安装Python 下面两个,然后自定义,全选 可以把前4个选上 3.环境配置 1)搜高级系统设置 2…...
mongodb源码分析session执行handleRequest命令find过程
mongo/transport/service_state_machine.cpp已经分析startSession创建ASIOSession过程,并且验证connection是否超过限制ASIOSession和connection是循环接受客户端命令,把数据流转换成Message,状态转变流程是:State::Created 》 St…...

vscode(仍待补充)
写于2025 6.9 主包将加入vscode这个更权威的圈子 vscode的基本使用 侧边栏 vscode还能连接ssh? debug时使用的launch文件 1.task.json {"tasks": [{"type": "cppbuild","label": "C/C: gcc.exe 生成活动文件"…...

dedecms 织梦自定义表单留言增加ajax验证码功能
增加ajax功能模块,用户不点击提交按钮,只要输入框失去焦点,就会提前提示验证码是否正确。 一,模板上增加验证码 <input name"vdcode"id"vdcode" placeholder"请输入验证码" type"text&quo…...

最新SpringBoot+SpringCloud+Nacos微服务框架分享
文章目录 前言一、服务规划二、架构核心1.cloud的pom2.gateway的异常handler3.gateway的filter4、admin的pom5、admin的登录核心 三、code-helper分享总结 前言 最近有个活蛮赶的,根据Excel列的需求预估的工时直接打骨折,不要问我为什么,主要…...

【单片机期末】单片机系统设计
主要内容:系统状态机,系统时基,系统需求分析,系统构建,系统状态流图 一、题目要求 二、绘制系统状态流图 题目:根据上述描述绘制系统状态流图,注明状态转移条件及方向。 三、利用定时器产生时…...
关于 WASM:1. WASM 基础原理
一、WASM 简介 1.1 WebAssembly 是什么? WebAssembly(WASM) 是一种能在现代浏览器中高效运行的二进制指令格式,它不是传统的编程语言,而是一种 低级字节码格式,可由高级语言(如 C、C、Rust&am…...

深入解析C++中的extern关键字:跨文件共享变量与函数的终极指南
🚀 C extern 关键字深度解析:跨文件编程的终极指南 📅 更新时间:2025年6月5日 🏷️ 标签:C | extern关键字 | 多文件编程 | 链接与声明 | 现代C 文章目录 前言🔥一、extern 是什么?&…...