python如何读写Excel
python如何读写excel
1.安装两个库
pip install xlrd xlwt
读取excel:
2.如何读取excel
import xlrd
book = xlrd.open_workbook('demo.xlsx')
sheet = book.sheet_by_index(0)
#获取有多少行多少列
print(sheet.nrows) #4
print(sheet.ncols) #4
print(sheet.cell(0,0)) #text:'姓名'
print(sheet.cell_value(0,0)) #姓名
print(sheet.row_values(0)) #['姓名', '语文', '数学', '外语']
print(sheet.row_values(1,1)) #[95.0, 99.0, 96.0]
3.如何读写excel
求分数的总和
import xlrd, xlwt
rbook = xlrd.open_workbook('demo.xlsx')
rsheet = rbook.sheet_by_index(0)
k = rsheet.ncols
#在最后添加一列 ‘总分’
rsheet.put_cell(0,k,xlrd.XL_CELL_TEXT, '总分', None)
for i in range(1,rsheet.nrows):
#求分数总和
t = sum(rsheet.row_values(i, 1))
rsheet.put_cell(i,k,xlrd.XL_CELL_NUMBER,t,None)
wbook = xlwt.Workbook()
wsheet = wbook.add_sheet(rsheet.name)
for i in range(rsheet.nrows):
for j in range(rsheet.ncols):
wsheet.write(i,j,rsheet.cell_value(i,j))
wbook.save('out.xlsx')
结果: