感谢aardio培训群:Kylin 分享源码

xlsx格式的excel文件是对xml的封包, 所以可以用string.xml库来处理这种格式文件的数据

下面是他提供的简单数字数据读取示例库excelx://excel_数字数据简单读取

import string.xml;

import zlib.zip

import zlib.unzip

import fsys;

import console;

class excelx{

ctor (xlsx, n=1) {

if xlsx and ..io.exist(..io.fullpath(xlsx)) {

..fsys.copy(..io.fullpath(xlsx),"~/temp.zip");

..zlib.unzip.extract( "~/temp.zip","~/tmp",

function(fileName,extractPath,fileInfo,size,unitSize,unitName){

if(extractPath){

return true;

}

}, , function(numEntries){}

)

try{

this = ..string.xml(..string.load("~/tmp/xl/worksheets/sheet"++n++".xml"))

this.data = this.queryEle({tagName="sheetData"})

this.rows = this.queryEles({tagName="row"})

this.cells = this.queryEles({tagName="c"})

this.totable_ = function(){

var tab = {}

for i,row in this.rows {

var r = {}

var cells = row.queryEles({tagName="c"})

for j,cell in cells {

var v = cell.innerText();

try {

v = tonumber(v)

}

..table.push(r, v)

}

..table.push(tab,r)

}

return tab;

}

this.tab = this.totable_()

}

catch (e) {

..console.dump(e);

..console.dump("读取excel文件失败! 程序退出!")

return null;

}

} elseif xlsx and !..io.exist(..io.fullpath(xlsx)) {

..console.dump(e);

..console.dump("读取excel文件失败! 程序退出!")

return null;

}

}

totable = function(){

return this.tab;

}

getCell = function(row,col){

if (type(row) == type.string) && (col == null) {

var v = this.queryEle({tagName="c"; r=row}).innerText();

try {

v = tonumber(v)

}

return v

} elseif (type(row) == type.number) && (type(col) == type.number){

var tab = owner.totable()

return tab[row][col]

}

}

getRow = function(row){

return this.tab[tonumber(row)]

}

getCol = function(col){

var cols = {}

if type(col) == type.number {

for _,row in this.tab {

..table.push(cols, row[col])

}

} elseif (type(col) == type.string) {

for _,cell in this.cells {

if ..string.find(cell.r,"^"++col++"\d+") {

var v = cell.innerText()

try {

v = tonumber(v)

}

..table.push(cols, v)

}

}

}

return cols;

}

}

注意: 使用的时候该库要放到工程lib库目录下,导入excelx即可import console

import excelx

xl=excelx("C:\demo.xlsx");

console.dump(xl.getRow(2))

console.dump(xl.getCol("C"))

console.log(xl.getCell("B1"))

console.dump(xl.totable())

console.pause()

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐