python3进行excel操作

前言

只要有需求,就会找出解决问题的方法

准备

pip install xlrd //读取表格
pip install xlwt //写入表格

写入数据

首先先初始化

import xlwt
excel = xlwt.Workbook(encoding='utf-8') #创建excel
sheet = excel.add_sheet('member') 		#创建sheet
style = xlwt.XFStyle()					#初始化样式

font = xlwt.Font()						#创建字体
font.name = u'微软雅黑' 					#字体类型
font.height = 400    		#字体大小   200等于excel字体大小中的10
style.font = font   		#设定样式

写入

sheet.write(0,0,'a')#写入不带字体样式的内容
sheet.write(0,0,'a',style)#写入带字体样式的内容

格子从(0,0)开始以此类推

读取数据

import xlrd
workbook = xlrd.open_workbook(FILE_PATH)
# 获取全部工作表(sheet)以及选取对应的工作表
sheet_name = workbook.sheet_names()[0]#将所有的sheet装到一个list中
host_sheet = workbook.sheet_by_name(sheet_name)#打开sheet
rows = host_sheet.nrows
cols = host_sheet.ncols
#遍历,你可以横着遍历也能竖着遍历
for i in range(rows):
	print(host_sheet.row_values(i))
for i in range(cols):
	print(host_sheet.col_values(i))

其他操作

#更改列宽和行高
import xlwt
book = xlwt.Workbook(encoding='utf-8')
sheet = book.add_sheet('sheet1')
for i in range(cols)#列宽
	sheet.col(i) = 256*20 
for i in range(rows)#行高
	sheet.row(i) = 256*20

备注

都是我目前用到的东西

发布了36 篇原创文章 · 获赞 29 · 访问量 3937

猜你喜欢

转载自blog.csdn.net/YUK_103/article/details/103903212