python处理excel 表格-Python读取Excel表格

本文将教大家如何使用Python来读取Excel表,学会这个技能对提高工作效率会十分有帮助。

目录:

1.安装Python读excel模块——xlrd

2.准备表格内容

3.编写python代码并运行

4.一些特殊的格式处理

1.安装xlrd

在python新安装好时,是没有安装excel处理组件的,需要通过命令行安装。在cmd窗口中输入:

pip install xlrd

等待安装完毕。

python处理excel 表格-Python读取Excel表格

2.准备表格内容

这里准备了一个示例表格截图,保存为test.xlsx待用。

python处理excel 表格-Python读取Excel表格

3.编写python代码并运行

在保存test.xlsx的位置上,新建一个readexcel.py文件,用记事本或其他文本编辑工具打开。

编程的整体思路为,打开文件,选定表格,读取行列内容,读取表格内数据,print。基本代码非常简单。

在文本编辑工具中输入如下代码,保存并关闭。

import xlrd

#打开文件wb = xlrd.open_workbook("test.xlsx")

#获取第一个表格

sheet1 = wb.sheet_by_index(0)

print(sheet1.cell(0,0).value)#打印第0行第0列的表格

print(sheet1.cell(0,1).value)

print(sheet1.cell(1,0).value)

print(sheet1.cell(1,1).value)

print(sheet1.cell(2,0).value)

print(sheet1.cell(2,1).value)

print(sheet1.cell(3,0).value)

print(sheet1.cell(3,1).value)

这里注意,每句的开头不可以有空格,因为python的缩进是用来表示编程的层次。

在保存test.xlsx的位置上打开cmd,运行 python readexcel.py

可以看到结果:

python处理excel 表格-Python读取Excel表格

4.一些特殊的格式处理

可以看到,print的"学号”格式不对,带了个".0”,这里需要对readexcel.py进行一些修改。

print(int(sheet1.cell_value(3,1))) 如上,在需要去除".0”的值上加上int()

import xlrdwb = xlrd.open_workbook("test.xlsx")#打开文件

sheet1 = wb.sheet_by_index(0)#获取第一个表格

print(sheet1.cell(0,0).value)#打印第0行第0列的表格

print(sheet1.cell(0,1).value)

print(sheet1.cell(1,0).value)

print(int(sheet1.cell(1,1).value))

print(sheet1.cell(2,0).value)

print(int(sheet1.cell(2,1).value))

print(sheet1.cell(3,0).value)

print(int(sheet1.cell_value(3,1)))

运行结果如下:

python处理excel 表格-Python读取Excel表格

免责声明:内容和图片源自网络,版权归原作者所有,如有侵犯您的原创版权请告知,我们将尽快删除相关内容。