python操作

用xlrd读取excel文件数据

安装并导入xlrd库:

pip install xlrd
import xlrd

读取excel文件:

 loc = ("绝对路径")   
wb = xlrd.open_workbook(loc)
sheet = wb.sheet_by_index(0)

打印excel表格第一行第一列:

>>>print(sheet.cell_value(0,0))

查看行数,列数:

>>>print(sheet.nrows)  
print(sheet.ncols)

打印所有列标签:

for i in range(sheet.ncols): 
  print(sheet.cell_value(0,1))

打印第一行内容:

>>>print(sheet.row_values(1))

使用xlwt写入excel

pip install xlwt
import xlwt
from xlwt import Workbook
wb = Workbook()
sheet1 = wb.add_sheet('Sheet 1')
sheet1.write(1,0,'姓名')
sheet1.write(1,0,'年龄')
sheet1.write(0,1,'序号1')
sheet1.write(0,2,'序号2')
wb.save('xlwt example.xls')

添加格式

import xlwt
workbook = xlwt.Workbook()
sheet = workvook.add_sheet("Sheet Name")
#先给单元格内容添加格式
style = xlwt.easyxf('font:bold 1,color:red')
#再在单元格内写入数据
sheet.write(0,0,'SAMPLE',style)
workbook.save("sample.xls")

你可能感兴趣的:(python操作)