转载: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文件进行写入操作:
- # -*- coding: UTF-8 -*-
- # How to write to an Excel using xlwt module
- import xlwt
- # 创建一个Workbook对象,这就相当于创建了一个Excel文件
- book = xlwt.Workbook(encoding='utf-8', style_compression=0)
- # 创建一个sheet对象,一个sheet对象对应Excel文件中的一张表格。
- # 在电脑桌面右键新建一个Excel文件,其中就包含sheet1,sheet2,sheet3三张表
- sheet = book.add_sheet('aa', cell_overwrite_ok=True) # 其中的aa是这张表的名字
- # 向表aa中添加数据
- sheet.write(0, 0, 'EnglishName') # 其中的'0, 0'指定表中的单元,'EnglishName'是向该单元写入的内容
- sheet.write(1, 0, 'Marcovaldo')
- txt1 = '中文名字'
- sheet.write(0, 1, txt1.decode('utf-8')) # 此处需要将中文字符串解码成unicode码,否则会报错
- txt2 = '马可瓦多'
- sheet.write(1, 1, txt2.decode('utf-8'))
- # 最后,将以上操作保存到指定的Excel文件中
- book.save(r'e:\try1.xls') #在字符串前加r,声明为raw字符串,这样就不会处理其中的转义了。否则,可能会报错
对Excel文件进行读取操作:
- # -*- coding: UTF-8 -*-
- # How to read from an Excel using xlrd module
- import xlrd
- # 打开指定路径中的xls文件
- xlsfile = r'e:\try1.xls'
- book = xlrd.open_workbook(xlsfile) # 得到Excel文件的book对象
- # 得到sheet对象
- sheet0 = book.sheet_by_index(0) # 通过sheet索引获得sheet对象
- sheet_name = book.sheet_names()[0] # 获得指定索引的sheet名字
- print sheet_name
- sheet1 = book.sheet_by_name(sheet_name) # 通过sheet名字来获取,当然如果知道sheet名字就可以直接指定
- # 获得行数和列数
- nrows = sheet0.nrows # 行总数
- ncols = sheet0.ncols # 列总数
- # 获得指定行、列的值,返回对象为一个值列表
- row_data = sheet0.row_values(0) # 获得第1行的数据列表
- print row_data
- col_data = sheet0.col_values(0) # 获得第1列的数据列表
- # 通过坐标读取表格中的数据
- cell_value1 = sheet0.cell_value(0, 0)
- print cell_value1
- cell_value2 = sheet0.cell_value(0, 1)
- print cell_value2