python简单读取excel文件
来源:互联网 发布:淘宝拒收退款流程 编辑:程序博客网 时间:2024/05/17 04:01
python简单读取excel文件
众所周知,python拥有强大的文本编辑能力,有时我们需要将其他格式的文本通过excel的方式呈现,以下我们来简单的认识下如何通过python将其他文本格式的内容转化为excel展示。
这里我们需要用到三个模块:xlrd xlwt xlutis
-http://pypi.python.org/pypi/xlrd
-http://pypi.python.org/pypi/xlwt
-http://pypi.python.org/pypi/xlutils
xlrd
python 一般用xlrd来读取excel文件,需要注意用xlrd读取excel是不能对其进行操作的。现在我有一个json结构需要将其中的一些字段放到excel文件中展示,如下:
{ "id": "01", "name": "name1", "data": [ { "id": "001", "start": 884000, "end": 886100 }, { "id": "002", "start": 1061199, "end": 1064500 }, { "id": "003", "start": 420399, "end": 422100 } ]}
将其中data中的数据存与excel表中。
当前场景中,假设我们已经新建了一个data.xls的表(注意当前库支持97-03版本的excel)
给出代码:
data = xlrd.open_workbook('data.xls')table = data.sheets()[0] #excel中的第一张表nrows = table.nrows #行数ncols = table.ncols #列数with open('test.json', 'r') as f: data = f.read()json_data = json.loads(data)index = 1for i in json_data.get('data'): table.put_cell(index, 1, 1, i.get('id'), xf) index = index + 1
如上操作自后发现数据并没有写入excel表中,原因上面已经说明
xlwt
在写入excel之前,初始化workbook对象,然后添加一个workbook对象
给出代码
import xlwtwbk = xlwt.Workbook()sheet = wbk.add_sheet('sheet', cell_overwrite_ok=True)sheet.write(0,0,'test')sheet.write(0,0,'test1')
xlutils
xlutils(依赖于xlrd和xlwt)提供复制excel文件内容和修改文件的功能。即在xlrd.Book和xlwt.Workbook之间建立了一个管道,如图
给出代码
data = xlrd.open_workbook('data.xls')wb = copy(data)ws = wb.get_sheet(0)with open('test.json', 'r') as f: data = f.read()json_data = json.loads(data)index = 1for i in json_data.get('data'): ws.write(index, 1, i.get('id')) ws.write(index, 2, gettime(i.get('start'))) ws.write(index, 3, i.get('start')) ws.write(index, 4, gettime(i.get('end'))) ws.write(index, 5, i.get('end')) index = index + 1wb.save('result.xls')
另说
将毫秒转为 时:分:秒 格式
def gettime(time): m, s = divmod(time/1000, 60) h, m = divmod(m, 60) return ("%02d:%02d:%02d" % (h, m, s))
参考
http://blog.csdn.net/tianzhu123/article/details/7225809
阅读全文
0 0
- python简单读取excel文件
- Python excel文件读取
- python读取excel文件
- python读取excel文件
- python读取excel文件
- python读取excel文件
- Python读取Excel文件
- python读取excel文件
- python 读取excel文件
- 简单的读取excel文件
- Python读取Microsoft Excel文件
- python 简单解析excel文件
- Python读取excel写入到RTF文件
- 读取excel文件并绘制图表[Python]
- 【python】 读取Excel文件并绘制图表
- Python读取excel文件(xlrd,xlwt)
- python读取excel文件(xrld模块)
- 【python】 读取Excel文件并绘制图表
- 联想小新510s安装mac OS X 10.11经验分享
- 小程序Java多次请求Session不变
- 应用密码学-1
- FTP常用命令
- 导入环信easaUI3.3.2历险记
- python简单读取excel文件
- jsp如何禁止使用session
- vim plug搭建
- python assert 断言详细用法格式
- LINUX wait
- java多线程面试
- FPGA中状态机实现需要注意的地方
- make: *** 没有规则可以创建“default”需要的目标“build”
- 游戏编程入门(5):使用键盘和鼠标控制游戏