Python读写Excel表格,就是这么简单粗暴又好用
off999 2024-11-07 11:39 15 浏览 0 评论
最近在做一些数据处理和计算的工作,因为数据是以.CSV格式保存的,因此刚开始直接用Excel来处理。
但是做着做着发现重复的劳动,其实并没有多大的意义,于是就想着写个小工具帮着处理。
以前正好在一本书上看到过,使用Python来处理Excel表格,可惜没有仔细看。
于是我到处查找资料,基本解决了日常所需,终于算是完成了任务,因此撰写此文就算是总结吧,主要记录使用过程的常见问题及解决。
Python操作Excel,主要用到xlrd和xlwt这两个库,即xlrd是读Excel,xlwt是写Excel的库。
可从这里下载https://pypi.python.org/pypi。下面分别记录Python读和写Excel。
- Python写Excel——xlwt
Python写Excel的难点,不在构造一个Workbook的本身,而是填充的数据,不过这不在范围内。
在写Excel的操作中,也有棘手的问题,比如写入合并的单元格,就是比较麻烦的,另外写入还有不同的样式。
详细代码如下:
<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">import xlwt
设置表格样式
def set_style(name,height,bold=False):
style = xlwt.XFStyle()
font = xlwt.Font()
font.name = name
font.bold = bold
font.color_index = 4
font.height = height
style.font = font
return style
写Excel
def write_excel():
f = xlwt.Workbook()
sheet1 = f.add_sheet('学生',cell_overwrite_ok=True)
row0 = ["姓名","年龄","出生日期","爱好"]
colum0 = ["张三","李四","恋习Python","小明","小红","无名"]
写第一行
for i in range(0,len(row0)):
sheet1.write(0,i,row0[i],set_style('Times New Roman',220,True))
写第一列
for i in range(0,len(colum0)):
sheet1.write(i+1,0,colum0[i],set_style('Times New Roman',220,True))
sheet1.write(1,3,'2006/12/12')
sheet1.write_merge(6,6,1,3,'未知')#合并行单元格
sheet1.write_merge(1,2,3,3,'打游戏')#合并列单元格
sheet1.write_merge(4,5,3,3,'打篮球')
f.save('test.xls')
if name == 'main':
write_excel()
</pre>
结果图:
在此,对write_merge()的用法稍作解释,如上述:sheet1.write_merge(1,2,3,3,'打游戏'),即在四列合并第2,3列,合并后的单元格内容为"合计",并设置了style。其中,里面所有的参数都是以0开始计算的。
- Python读Excel——xlrd
Python读取Excel表格,相比xlwt来说,xlrd提供的接口比较多,但过程也有几个比较麻烦的问题,比如读取日期、读合并单元格内容。
下面先看看基本的操作:
(图表数据)
整体思路为,打开文件,选定表格,读取行列内容,读取表格内数据
详细代码如下:
<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">import xlrd
from datetime import date,datetime
file = 'test3.xlsx'
def read_excel():
wb = xlrd.open_workbook(filename=file)#打开文件
print(wb.sheet_names())#获取所有表格名字
sheet1 = wb.sheet_by_index(0)#通过索引获取表格
sheet2 = wb.sheet_by_name('年级')#通过名字获取表格
print(sheet1,sheet2)
print(sheet1.name,sheet1.nrows,sheet1.ncols)
rows = sheet1.row_values(2)#获取行内容
cols = sheet1.col_values(3)#获取列内容
print(rows)
print(cols)
print(sheet1.cell(1,0).value)#获取表格里的内容,三种方式
print(sheet1.cell_value(1,0))
print(sheet1.row(1)[0].value)
</pre>
运行结果如下:
那么问题来了,上面的运行结果中红框框中的字段明明是出生日期,可显示的确实浮点数;同时合并单元格里面应该是有内容的,结果不能为空。
别急,我们来一一解决这两个问题:
1.Python读取Excel中单元格内容为日期的方式
Python读取Excel中单元格的内容返回的有5种类型,即上面例子中的ctype:
ctype : 0 empty,1 string,2 number, 3 date,4 boolean,5 error
即date的ctype=3,这时需要使用xlrd的xldate_as_tuple来处理为date格式,先判断表格的ctype=3时xldate才能开始操作。
详细代码如下:
<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">import xlrd
from datetime import date,datetime
print(sheet1.cell(1,2).ctype)
date_value = xlrd.xldate_as_tuple(sheet1.cell_value(1,2),wb.datemode)
print(date_value)
print(date(date_value[:3]))
print(date(date_value[:3]).strftime('%Y/%m/%d'))
</pre>
运行结果如下:
2.获取合并单元格的内容
在操作之前,先介绍一下merged_cells()用法,merged_cells返回的这四个参数的含义是:(row,row_range,col,col_range),其中[row,row_range)包括row,不包括row_range,col也是一样,即(1, 3, 4, 5)的含义是:第1到2行(不包括3)合并,(7, 8, 2, 5)的含义是:第2到4列合并。
详细代码如下:
<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">print(sheet1.merged_cells)
print(sheet1.cell_value(1,3))
print(sheet1.cell_value(4,3))
print(sheet1.cell_value(6,1))
</pre>
运行结果如下:
**发现规律了没?是的,获取merge_cells返回的row和col低位的索引即可! **于是可以这样批量获取:
详细代码如下:
<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">merge = []
print(sheet1.merged_cells)
for (rlow,rhigh,clow,chigh) in sheet1.merged_cells:
merge.append([rlow,clow])
for index in merge:
print(sheet1.cell_value(index[0],index[1]))
</pre>
运行结果跟上图一样,如下:
Python读写Excel表格,就是这么简单粗暴又好用,如果觉得不错,对你工作中有帮助,动动手指分享给更多人哦。
本文就到这里啦,喜欢python可以关注我们哦!
相关推荐
- Python四种常用的高阶函数,你会用了吗
-
每天进步一点点,关注我们哦,每天分享测试技术文章本文章出自【码同学软件测试】码同学公众号:自动化软件测试码同学抖音号:小码哥聊软件测试1、什么是高阶函数把函数作为参数传入,这样的函数称为高阶函数例如:...
- Python之函数进阶-函数加强(上)(python函数的作用增强代码的可读性)
-
一.递归函数递归是一种编程技术,其中函数调用自身以解决问题。递归函数需要有一个或多个终止条件,以防止无限递归。递归可以用于解决许多问题,例如排序、搜索、解析语法等。递归的优点是代码简洁、易于理解,并...
- 数据分析-一元线性回归分析Python
-
前面几篇介绍了数据的相关性分析,通过相关性分析可以看出变量之间的相关性程度。如果我们已经发现变量之间存在明显的相关性了,接下来就可以通过回归分析,计算出具体的相关值,然后可以用于对其他数据的预测。本篇...
- python基础函数(python函数总结)
-
Python函数是代码复用的核心工具,掌握基础函数的使用是编程的关键。以下是Python函数的系统总结,包含内置函数和自定义函数的详细用法,以及实际应用场景。一、Python内置函数(...
- python进阶100集(9)int数据类型深入分析
-
一、基本概念int数据类型基本上来说这里指的都是整形,下一届我们会讲解整形和浮点型的转化,以及精度问题!a=100b=a这里a是变量名,100就是int数据对象,b指向的是a指向的对象,...
- Python学不会来打我(73)python常用的高阶函数汇总
-
python最常用的高阶函数有counter(),sorted(),map(),reduce(),filter()。很多高阶函数都是将一个基础函数作为第一个参数,将另外一个容器集合作为第二个参数,然...
- python中有哪些内置函数可用于编写数值表达式?
-
在Python中,用于编写数值表达式的内置函数很多,它们可以帮助你处理数学运算、类型转换、数值判断等。以下是常用的内置函数(不需要导入模块)按类别归类说明:一、基础数值处理函数函数作用示例ab...
- 如何在Python中获取数字的绝对值?
-
Python有两种获取数字绝对值的方法:内置abs()函数返回绝对值。math.fabs()函数还返回浮点绝对值。abs()函数获取绝对值内置abs()函数返回绝对值,要使用该函数,只需直接调用:a...
- 【Python大语言模型系列】使用dify云版本开发一个智能客服机器人
-
这是我的第359篇原创文章。一、引言上篇文章我们介绍了如何使用dify云版本开发一个简单的工作流:【Python大语言模型系列】一文教你使用dify云版本开发一个AI工作流(完整教程)这篇文章我们将引...
- Python3.11版本使用thriftpy2的问题
-
Python3.11于2022年10月24日发布,但目前thriftpy2在Python3.11版本下无法安装,如果有使用thriftpy2的童鞋,建议晚点再升级到最新版本。...
- uwsgi的python2+3多版本共存(python多版本兼容)
-
一、第一种方式(virtualenv)1、首先,机器需要有python2和python3的可执行环境。确保pip和pip3命令可用。原理就是在哪个环境下安装uwsgi。uwsgi启动的时候,就用的哪个...
- 解释一下Python脚本中版本号声明的作用
-
在Python脚本中声明版本号(如__version__变量)是一种常见的元数据管理实践,在IronPython的兼容性验证机制中具有重要作用。以下是版本号声明的核心作用及实现原理:一、版本号...
- 除了版本号声明,还有哪些元数据可以用于Python脚本的兼容性管理
-
在Python脚本的兼容性管理中,除了版本号声明外,还有多种元数据可以用于增强脚本与宿主环境的交互和验证。以下是一些关键的元数据类型及其应用场景:一、环境依赖声明1.Python版本要求pyth...
- 今年回家没票了?不,我有高科技抢票
-
零基础使用抢票开源软件Py12306一年一度的抢票季就要到了,今天给大家科普一下一款软件的使用方法。软件目前是开源的,禁止用于商用。首先需要在电脑上安装python3.7,首先从官网下载对应的安装包,...
- 生猛!春运抢票神器成GitHub热榜第一,过年回家全靠它了
-
作者:车栗子发自:凹非寺量子位报道春节抢票正在如火如荼的进行,过年回家那肯定需要抢票,每年的抢票大战,都是一场硬战,没有一个好工具,怎么能上战场死锁呢。今天小编推荐一个Python抢票工具,送到...
你 发表评论:
欢迎- 一周热门
- 最近发表
- 标签列表
-
- python计时 (73)
- python安装路径 (56)
- python类型转换 (93)
- python进度条 (67)
- python吧 (67)
- python字典遍历 (54)
- python的for循环 (65)
- python格式化字符串 (61)
- python静态方法 (57)
- python列表切片 (59)
- python面向对象编程 (60)
- python 代码加密 (65)
- python串口编程 (60)
- python读取文件夹下所有文件 (59)
- java调用python脚本 (56)
- python操作mysql数据库 (66)
- python获取列表的长度 (64)
- python接口 (63)
- python调用函数 (57)
- python多态 (60)
- python匿名函数 (59)
- python打印九九乘法表 (65)
- python赋值 (62)
- python异常 (69)
- python元祖 (57)