python读写Excel表格

读xls要用到xlrd模块:

pip install xlrd

写xls要用到xlwt模块:

pip install xlwt

注:这两个模块读写Excel表格不支持xlsx格式,只支持xls格式,要操作xlsx表格需要转换为xls。

主要方法:

读xls:

import xlrd
​
#打开xls
book = xlrd.open_workbook(xls_name)     
#获取sheet1
sheet1 = book.sheets()[0]               
​
#行数
rows = sheet1.nrows                     
#列数
cols = sheet1.ncols                     
​
#获取row行,col列的数据
value = sheet1.cell(row,col).value      
#row行,col列的数据类型,0 empty,1 string,2 number,3 date,4 boolean,5 error
type = sheet1.cell(row,col).ctype

写xls:

import xlwt
​
book = xlwt.Workbook()
#创建sheet1
sheet1 = book.add_sheet(u'sheet1',cell_overwrite_ok=True)   
​
#向row行,col列写入数据
sheet1.write(row,col,value)                                 
#合并单元格,从rows行,合并x行,从cols列,合并y列
sheet1.write_merge(rows, rows+x, cols, cols+y, value)       
​
#保存xls
book.save(xls_name)

 

posted @ 2021-11-15 11:36  elon_wang  阅读(82)  评论(0编辑  收藏  举报