这里有新鲜出炉的 Python 多线程编程,程序狗速度看过来!
Python 是一种面向对象、解释型计算机程序设计语言,由 Guido van Rossum 于 1989 年底发明,第一个公开发行版发行于 1991 年。Python 语法简洁而清晰,具有丰富和强大的类库。它常被昵称为胶水语言,它能够把用其他语言制作的各种模块(尤其是 C/C++)很轻松地联结在一起。
学习 Python 的过程中,我们会遇到 Excel 的读写问题。这时,我们可以使用 xlwt 模块将数据写入 Excel 表格中,使用 xlrd 模块从 Excel 中读取数据。下面我们介绍如何实现使用 Python 对 Excel 进行读写操作。
学习 Python 的过程中,我们会遇到 Excel 的读写问题。这时,我们可以使用 xlwt 模块将数据写入 Excel 表格中,使用 xlrd 模块从 Excel 中读取数据。下面我们介绍如何实现使用 Python 对 Excel 进行读写操作。
Python 版:3.5.2
通过 pip 安装 xlwt,xlrd 这两个模块,如果没有安装的话:
pip install xlwt
pip install xlrd
一、对 Excel 文件进行写入操作:
- # -*- conding:utf-8 -*-
- __author__ = 'mayi'
- #How to write to an Excel using xlwt module
- import xlwt
- #创建一个Wordbook对象,相当于创建了一个Excel文件
- book = xlwt.Workbook(encoding = "utf-8", style_compression = 0)
- #创建一个sheet对象,一个sheet对象对应Excel文件中的一张表格
- sheet = book.add_sheet("sheet1", cell_overwrite_ok = True)
- #向表sheet1中添加数据
- sheet.write(0, 0, "EnglishName") #其中,"0, 0"指定表中的单元格,"EnglishName"是向该单元格中写入的内容
- sheet.write(1, 0, "MaYi")
- sheet.write(0, 1, "中文名字")
- sheet.write(1, 1, "蚂蚁")
- #最后,将以上操作保存到指定的Excel文件中
- book.save("name.xls")
二、对 Excel 文件进行读取操作:
- # -*- conding:utf-8 -*-
- __author__ = 'mayi'
- # How to read from an Excel using xlrd module
- import xlrd
- # 打开指定路径中的xls文件,得到book对象
- xls_file = "name.xls"
- #打开指定文件
- book = xlrd.open_workbook(xls_file)
- # 通过sheet索引获得sheet对象
- sheet1 = book.sheet_by_index(0)
- # # 获得指定索引的sheet名
- # sheet1_name = book.sheet_names()[0]
- # print(sheet1_name)
- # # 通过sheet名字获得sheet对象
- # sheet1 = book.sheet_by_name(sheet1_name)
- # 获得行数和列数
- # 总行数
- nrows = sheet1.nrows
- #总列数
- ncols = sheet1.ncols
- # 遍历打印表中的内容
- for i in range(nrows):
- for j in range(ncols):
- cell_value = sheet1.cell_value(i, j)
- print(cell_value, end = "\t")
- print("")
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持 PHPERZ!
来源: http://www.phperz.com/article/17/0519/332911.html