xldr的简单使用

2018-07-19  本文已影响0人  龙凕

需要处理excel里配表的数据,ms的产品数据格式不是很简单,直接操作有点麻烦。基本上这种活就直接上python了。我不用了解也知道肯定有包。xlrd是一个python的包,可以方便的操作excel里的数据。

最简单操作流程:
首先import xlrd
然后用xlrd.open_work(filename)来打开.xlsx文件
接着使用sheet_by_name(sheetname)来打开工作表,也可以用sheet_by_index(0),直接索引sheets()[0]
sheet.nrows可以用于遍历这个sheet中每一行数据,同理ncols获取列
sheet.row_values(row)可以用来遍历row里面的每个item的数据,同理col_values
然后各种操作一番之后,自己保存

以上是读数据,如果想反手写excel,重点在于确定具体的单元格,使用cell(x,y).value读取,使用put_cell(row,col, value,xf)
xf是扩展格式,自行理解吧
In cell XFs, flag==0 means the attributes of the parent style XF are used, (but only if the attributes are valid there); flag==1 means the attributes of this XF are used.

格式的问题
基本上就是转utf-8的问题,只要unicode(item).encode("utf-8")就行,或者转别的也ojbk

一个简单的代码:

import xlrd
import csv
import os, shutil

def csv_from_excel():
    dstPath = "../outputassets/share_assetbundles/ios/data/"

    for file in os.listdir('.'):

        if os.path.isfile(file) and os.path.splitext(file)[1]=='.xlsx' : 

            #open workbook
            wb = xlrd.open_workbook(file)

            #find target sheet
            sh = wb.sheet_by_name('Sheet1')

            #create corresponding csv file
            csv_name = dstPath + os.path.splitext(file)[0] + '.csv'
            csv_name_android = androidPath + os.path.splitext(file)[0] + '.csv'
            
            your_csv_file = open(csv_name, 'wb')
            wr = csv.writer(your_csv_file)
            for rownum in xrange(sh.nrows):
                line = []
                for entry in sh.row_values(rownum):
                    if isinstance(entry, float):
                        entry_int = int(entry)
                        if entry_int == entry:
                            line.append(entry_int)
                    else:
                        line.append(unicode(entry).encode("utf-8"))
                wr.writerow(line)
            your_csv_file.close()
            



if __name__ == '__main__':
    csv_from_excel()
上一篇 下一篇

猜你喜欢

热点阅读