网络编程
位置:首页>> 网络编程>> Python编程>> python 读写excel文件操作示例【附源码下载】

python 读写excel文件操作示例【附源码下载】

作者:轻舞肥羊  发布时间:2023-02-20 09:26:31 

标签:python,读写excel文件

本文实例讲述了python 读写excel文件操作。分享给大家供大家参考,具体如下:

对excel文件的操作,python有第三方的工具包支持,xlutils,在这个工具包中包含了xlrd,xlwt等工具包.利用这些工具,可以方便的对excel 进行操作。

1. 下载 xlutils : http://pypi.python.org/pypi/xlutils

2. 安装,解压下载文件之后,可以 python setup.py install

3. 应用(生成EXCEL,遍历EXCEL,修改EXCEL,属性控制,日期控制等)。

1) 创建 EXCEL 文件


from tempfile import TemporaryFile
from xlwt import Workbook
book = Workbook()
sheet1 = book.add_sheet('Sheet 1')
book.add_sheet('Sheet 2')
sheet1.write(0,0,'A1')
sheet1.write(0,1,'B1')
row1 = sheet1.row(1)
row1.write(0,'A2')
row1.write(1,'B2')
sheet1.col(0).width = 10000
sheet2 = book.get_sheet(1)
sheet2.row(0).write(0,'Sheet 2 A1')
sheet2.row(0).write(1,'Sheet 2 B1')
sheet2.flush_row_data()
sheet2.write(1,0,'Sheet 2 A3')
sheet2.col(0).width = 5000
sheet2.col(0).hidden = True
book.save('simple.xls')
book.save(TemporaryFile())

这样就生成了simple.xls 文件.

2) 循环遍历EXCEL文件


import xlrd
import xlutils.copy
import os
if __name__ == '__main__':
 wb = xlrd.open_workbook('simple.xls')  
 for s in wb.sheets():
   print 'Sheet:',s.name
   for row in range(s.nrows):
     values = []
     for col in range(s.ncols):
       values.append(s.cell(row,col).value)
     print ','.join(values)
   print

遍历整个excel 并打印出数据

3) 修改EXCEL


import xlrd
import xlutils.copy
import os
if __name__ == '__main__':
 template = "simple.xls"
 workBook = xlrd.open_workbook(template,formatting_info=True)
 workBook = xlutils.copy.copy(workBook)
 sheet = workBook.get_sheet(0)
 sheet.write(0, 0, '111')
 sheet.write(0, 1, '222')
 sheet.write(1, 0, '333')
 sheet.write(1, 1, '444')  
 workBook.save('simple.xls')

完整实例代码点击此处本站下载

希望本文所述对大家Python程序设计有所帮助。

来源:http://www.yihaomen.com/article/python/300.htm

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com