python读写excel前需要先安装对应的库,读excel需要安装xlrd库:

pip install xlrd

而写excel文件需要安装xlwt库:

pip install xlwt

python端从excel读取内容,或者写内容到excel,都是以DataFrame的

格式,所以还需要安装pandas库:

pip install pandas

写excel操作:

写excel的操作相对简单,准备好DataFrame格式的数据后,再调用to_excel方法即可。示例代码如下:

import pandas as pd

x=pd.DataFrame(data)

##将x中的数据写入名为data.xls的文件;

x.to_excel(‘data.xls’)

##将x中的数据写入名为data.xls的文件,表单名为sheet1

x.to_excel(‘data.xls’, sheet_name=’sheet1’)

读excel操作:

读excel主要分为打开文件,读取表格,读取行列,读取单元格等操作。打开文件的命令:

book = xlrd.open_workbook(filename)

读取第一个表的操作:

sheet1 = book.sheets()[0]

读取表单的第一列数据:

firstcol = sheet1.col_values(0)

读取表单的第二列数据:

secondcol = sheet1.col_values(1)

读取表单的第一行数据:

firstrow = sheet1.row_values(0)

读取表单的第二行数据:

secondrow = sheet1.row_values(1)

如何读取表单特定单元的数据:

table.cell(rowx, colx)