感谢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()