Python 操作Excel 主要会用到 xlrd 和 xlwt 两个库,xlrd 是读取Excel文件的库函数,xlwt是写Excel文件的库函数
一、Python读取excel—xlrd
首先读取一个Excel文件,该Excel文件中包含了两个sheet,名称分别为“Plain Water”、“Instant noodles”
1、Python对Excel的基本操作如下:
# coding = utf-8
import xlrd
def read_excel():
# 打开Excel文件
excel_file = xlrd.open_workbook("test.xls")
# 获得Excel的所有sheet,返回一个sheet名称的列表
file_sheets = excel_file.sheet_names() # ['Plain Water','Instant noodles']
# 获得指定的sheet名称
file_sheet = excel_file.sheet_names()[1] # Instant noodles
# 通过索引或者sheet名称获取sheet内容
sheet_content = excel_file.sheet_by_index(1) # Instant noodles 的内容
sheet_content = excel_file.sheet_by_name("Instant noodles")
# sheet 表的行数、列数、sheet名
rows = sheet_content.nrows
columns = shee_content.ncols
sheet_name = sheet_content.name
# 获取整行内容的,返回的值是一个数组
row_content = sheet_content.row_values(0) # 获取第一行的内容
# 获取整列的内容,返回一个数组
column_content = sheet_content.col_values(0) # 获取第一列
# 获取单元格的内容
cell_content = sheet_content.cell(0, 0).value # 获取Excel的第一个单元格的内容
二、Python 写Excel—xlwt
首先构思一下,欲写入Excel的sheet 名字为“Fruit”,Excel文件名称为“I love fruit.xls”
import xlwt
# 创建一个Excel文件
book = xlwt.Work_book()
# 工作表中添加一个sheet页
Fruit = book.add_sheet("Fruit", cell_overwrite_ok=True)
# 在Fruitsheet中写入内容(水果名称)
Fruit.write(0,0,"Apple) --sheet页中第一个表格中写入“Apple"
Fruit.write(0,1,"banana") -- 第1行第二列中写入“banana”
# 保存Excel文件,命名为I Love Fruit.xls
book.save("I Love Fruit.xls")