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

備註

都是我目前用到的東西

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章