利用Python处理Excel数据——xlrd,xlwt库

当面对成百上千个excel文件,需要重复读写时,你会不会很头大呢?

与其花费好几天去做这些繁琐无意义的操作,不如学学python如何批量读写excel文件,以下介绍用xlrd和xlwt库处理Excel数据。

我们新建一个excel表格(table1.xlsx)用于案例讲解:

一、使用xlrd库读取excel数据

1、python读取excel文件特定数据

import xlrd

data = xlrd.open_workbook(r'E:\Anaconda\data\hc200115\table1.xlsx') # 打开xlsx文件(绝对路径)
table = data.sheets()[0] # 打开第一张表
nrows = table.nrows # 获取表的行数

# 循环逐行输出
for i in range(nrows): 
   print(table.row_values(i)[:4]) # 取前四列数据
['Name', 'Age', 'Class', 'Score']
['Tom', 19.0, 162061.0, 80.0]
['Jack', 20.0, 172051.0, 90.0]
['Alan', 18.0, 150461.0, 100.0]
# Excel数据的行、列数
nrows=table.nrows
ncols=table.ncols
print(nrows)
print(ncols)
4
4

(注)打开xlsx文件时相对路径与绝对路径区别:

data = xlrd.open_workbook(r'E:\Anaconda\data\hc200115\table1.xlsx')   # 绝对路径
data = xlrd.open_workbook('table1.xlsx')                                                  # 相对路径(当前工作目录下)


2、python读取读取excel文件所有数据

import xlrd
#打开一个xls文件
workbook = xlrd.open_workbook('table1.xlsx')

#抓取所有sheet页的名称
worksheets = workbook.sheet_names()
print('worksheets is %s' %worksheets)
worksheets is ['Sheet1']
#定位到sheet1
worksheet1 = workbook.sheet_by_name(u'Sheet1')

#遍历sheet1中所有行row
num_rows = worksheet1.nrows
for curr_row in range(num_rows):
    row = worksheet1.row_values(curr_row)
    print('row%s is %s' %(curr_row,row))

#遍历sheet1中所有列col
num_cols = worksheet1.ncols
for curr_col in range(num_cols):
    col = worksheet1.col_values(curr_col)
    print('col%s is %s' %(curr_col,col))
row0 is ['Name', 'Age', 'Class', 'Score']
row1 is ['Tom', 19.0, 162061.0, 80.0]
row2 is ['Jack', 20.0, 172051.0, 90.0]
row3 is ['Alan', 18.0, 150461.0, 100.0]
col0 is ['Name', 'Tom', 'Jack', 'Alan']
col1 is ['Age', 19.0, 20.0, 18.0]
col2 is ['Class', 162061.0, 172051.0, 150461.0]
col3 is ['Score', 80.0, 90.0, 100.0]
#遍历sheet1中所有单元格cell
for rown in range(num_rows):
    for coln in range(num_cols):
        cell = worksheet1.cell_value(rown,coln)
        print(cell)
Name
Age
Class
Score
Tom
19.0
162061.0
80.0
Jack
20.0
172051.0
90.0
Alan
18.0
150461.0
100.0

二、使用xlwt库来写入excel数据

import xlwt

#创建workbook和sheet对象
workbook = xlwt.Workbook() #注意Workbook的开头W要大写
sheet1 = workbook.add_sheet('sheet1',cell_overwrite_ok=True)

#向sheet页中写入数据
sheet1.write(0,0,'Name1')
sheet1.write(0,1,'aaaa')
sheet1.write(1,0,'Name2')
sheet1.write(1,1,'bbbb')

#保存该excel文件,有同名文件时直接覆盖
workbook.save('test.xlsx')

print('创建excel文件完成!')
创建excel文件完成!

(在工作目录下生成“test.xlsx”文件)

发布了55 篇原创文章 · 获赞 122 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_40431584/article/details/103983643