python读写Excel

python读写Excel表格,主要使用xlwt ,xlrd两个模块

xlwt:写入Excel表格模块(xlwt只能写入xls文件,不能写入xlsx文件)

 #首先导入写模块

>>> import xlwt

#添加工作簿
>>> f=xlwt.Workbook(encoding="utf-8")

#添加一个sheet
>>> sheet1=f.add_sheet('学生',cell_overwrite_ok=True)

#向表格对应的坐标添加内容(第一个参数为行的坐标,第二个参数为列的坐标,第三个参数为坐标值,第四个参数是设置单元格样式)

 sheet1.write(0,i,row0[i],set_style('Times New Roman',220,True))

 如果要合并单元格使用如下方式:

1:参数1/参数2:行数

2:参数2/参数3:列数

下面的案列是将第1行到第2行,和第0列到第3列进行合并

保存 

f.save(‘demo') 


 

合并单元格操作:

xlrd:读取Excel表格模块

#先导入模块

import xlrd

#打开要读取的文件

 workbook=xlrd.open_workbook(file)

 

sheet1=workbook.sheet_by_index(0)
#表格名称,行数,列数
print(sheet1.name,sheet1.nrows,sheet1.ncols)
#得到第3行内容
rows=sheet1.row_values(3)
#得到第2列内容
cols=sheet1.col_values(2)
print(rows)

#输出单元格内容的3种方法
#输出第1行第2列的内容
print(sheet1.cell(1,2).value.encode("utf-8"))
#输出第2行第2列的内容
print(sheet1.cell_value(2,2).encode("utf-8"))
#输出第3行第2列的内容
print(sheet1.row(3)[2].value.encode("utf-8"))



 

 


原文地址:https://www.cnblogs.com/gaoyuxia/p/10530901.html