当前位置: 移动技术网 > IT编程>脚本编程>Python > python 读写excel文件操作示例【附源码下载】

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

2019年07月19日  | 移动技术网IT编程  | 我要评论

浙江省人事网,女英烈受刑,丁丁历险记全集

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

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

1. 下载 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相关内容感兴趣的读者可查看本站专题:《python操作excel表格技巧总结》、《python文件与目录操作技巧汇总》、《python文本文件操作技巧汇总》、《python数据结构与算法教程》、《python函数使用技巧总结》、《python字符串操作技巧汇总》及《python入门与进阶经典教程

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

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网