【python】读写excel

来源:互联网 发布:方腊手下大将排名 知乎 编辑:程序博客网 时间:2024/04/30 02:30

转载:http://blog.csdn.net/majordong100/article/details/50708365

学习Python的过程中,我们会遇到Excel的读写问题。通过搜索得知,我们可以使用xlwt module将数据写入Excel表格,使用xlrd module从Excel读取数据。下面介绍如何实现使用Python对Excel进行读写操作。


Python版本:2.7.11

通过pip安装xlwt, xlrd这两个模块,如果没有安装的话:

pip install xlwt

pip insall xlrd


对Excel文件进行写入操作:

[python] view plain copy
  1. # -*- coding: UTF-8 -*-  
  2. # How to write to an Excel using xlwt module  
  3. import xlwt  
  4. # 创建一个Workbook对象,这就相当于创建了一个Excel文件  
  5. book = xlwt.Workbook(encoding='utf-8', style_compression=0)  
  6.   
  7. # 创建一个sheet对象,一个sheet对象对应Excel文件中的一张表格。  
  8. # 在电脑桌面右键新建一个Excel文件,其中就包含sheet1,sheet2,sheet3三张表  
  9. sheet = book.add_sheet('aa', cell_overwrite_ok=True)    # 其中的aa是这张表的名字  
  10.   
  11. # 向表aa中添加数据  
  12. sheet.write(00'EnglishName')    # 其中的'0, 0'指定表中的单元,'EnglishName'是向该单元写入的内容  
  13. sheet.write(10'Marcovaldo')  
  14. txt1 = '中文名字'  
  15. sheet.write(01, txt1.decode('utf-8')) # 此处需要将中文字符串解码成unicode码,否则会报错  
  16. txt2 = '马可瓦多'  
  17. sheet.write(11, txt2.decode('utf-8'))  
  18.   
  19. # 最后,将以上操作保存到指定的Excel文件中  
  20. book.save(r'e:\try1.xls'#在字符串前加r,声明为raw字符串,这样就不会处理其中的转义了。否则,可能会报错  


对Excel文件进行读取操作:

[python] view plain copy
  1. # -*- coding: UTF-8 -*-  
  2. # How to read from an Excel using xlrd module  
  3. import xlrd  
  4. # 打开指定路径中的xls文件  
  5. xlsfile = r'e:\try1.xls'  
  6. book = xlrd.open_workbook(xlsfile)  # 得到Excel文件的book对象  
  7.   
  8. # 得到sheet对象  
  9. sheet0 = book.sheet_by_index(0)     # 通过sheet索引获得sheet对象  
  10. sheet_name = book.sheet_names()[0]  # 获得指定索引的sheet名字  
  11. print sheet_name  
  12. sheet1 = book.sheet_by_name(sheet_name)     # 通过sheet名字来获取,当然如果知道sheet名字就可以直接指定  
  13.   
  14. # 获得行数和列数  
  15. nrows = sheet0.nrows    # 行总数  
  16. ncols = sheet0.ncols    # 列总数  
  17.   
  18. # 获得指定行、列的值,返回对象为一个值列表  
  19. row_data = sheet0.row_values(0)     # 获得第1行的数据列表  
  20. print row_data  
  21. col_data = sheet0.col_values(0)     # 获得第1列的数据列表  
  22.   
  23. # 通过坐标读取表格中的数据  
  24. cell_value1 = sheet0.cell_value(00)  
  25. print cell_value1  
  26. cell_value2 = sheet0.cell_value(01)  
  27. print cell_value2  


0 0
原创粉丝点击