百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术资源 > 正文

Python读写Excel表格,就是这么简单粗暴又好用

off999 2024-11-07 11:39 17 浏览 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可以关注我们哦!

相关推荐

苹果ios14系统下载(苹果ios14.1下载)
苹果ios14系统下载(苹果ios14.1下载)

1方法一步骤/方式一打开Appstore。步骤/方式二在搜索栏点击搜索框。步骤/方式三搜索并点击需要下载的软件。步骤/方式四点击获取。步骤/方式五最后验证ID密码即可。1.在应用商店搜索你要下载的应用名称。2.点击下载按钮,如果要求登...

2025-11-19 03:03 off999

office2010怎么免费永久激活密钥

用这个试试,一个KMS激活工具可以激活2010到2019的Office自家的目前用的就是这个microsoft6477.moe/1716.html直接使用这个Microsoftoffice2010...

类似爱加速的国内ip(类似爱加速的app)
类似爱加速的国内ip(类似爱加速的app)

推荐“V8盒子”。这一款免费无广告的模拟器,不同于其它软件盒子,而是类似于X8沙箱,满足游戏多开,画中画,悬浮球操作,熄屏后台运行等多功能的沙箱盒子.支持一键root,一键安装xposed框架,能在安卓/苹果手机上运行多个安卓/ios虚拟系...

2025-11-19 02:03 off999

阿里旺旺手机客户端(阿里旺旺手机app)

手机淘宝的旺旺在打开商品后,会看到左下角有个旺旺的图标,点击就可以联系了。  阿里旺旺是将原先的淘宝旺旺与阿里巴巴贸易通整合在一起的一个新品牌。它是淘宝和阿里巴巴为商人量身定做的免费网上商务沟通软件,...

最纯净的pe装机工具(pe工具哪个纯净)

U盘装系统步骤:1.制作U盘启动盘。这里推荐大白菜U盘启动盘制作工具,在网上一搜便是。2.U盘启动盘做好了,我们还需要一个GHOST文件,可以从网上下载一个ghost版的XP/WIN7/WIN8系统,...

装一个erp系统多少钱(wms仓库管理软件)

现在主流有客户端ERP和云端ERP两种客户端通常一次买断,价格在万元左右,但是还有隐性费用,你需要支付服务器、数据管理员,此外如果系统需要更新维护,你还需要支付另外一笔不菲的费用。云端ERP:优势...

cad2014序列号和密钥永久(autocad2014序列号和密钥)

1在cad2014中修改标注样式后,需要将其保存2单击“样式管理器”按钮,在弹出的窗口中选择修改后的标注样式,然后单击“设置为当前”按钮,再单击“保存当前样式”按钮,将其保存为新的样式名称3为了...

qq修改密保手机号(qq修改密保手机号是什么意思)

QQ更改绑定的手机号码操作步骤如下:1、打开手机主界面,找到“QQ”软件点击打开。2、输入正确的QQ账户和密码登录到qq主界面。3、点击左上角的头像“图片”,进入到个人中心界面。4、进入到个人中心界面...

dell笔记本客服电话(dell笔记本客服电话人工服务)

戴尔中国的官方网站http://www.dell.com/zh-cn。通过这个网站购买的都没有问题;有问题也可以进入官网联系售后客服,也可以拔打dell电脑说明书上的售后热线,都可以为你解决的。还是建...

联想乐商店app官方下载(联想乐商店在哪下载)

您好!很遗憾!若是您的手机联想乐商店和联想游戏中心只能有流量,建议您核实是否乐安全有限制wifi上网,核实您所使用的wifi是否本身有限制。若还是无效,可清除缓存数据;备份资料恢复出厂设置尝试。欢迎您...

fat32u盘(FAT32u盘多少钱一个)
  • fat32u盘(FAT32u盘多少钱一个)
  • fat32u盘(FAT32u盘多少钱一个)
  • fat32u盘(FAT32u盘多少钱一个)
  • fat32u盘(FAT32u盘多少钱一个)
不用拉网线的路由器是真的吗

是真的不插卡不拉线有线就有网,这11个字其实就涵盖了无线路由器的特点,无线路由器免插卡、不用拉网线,完全摆脱了之前家用路由器和网线捆绑的模式,有电就有网,其实说的就是无线路由器的使用操作简单,通电就可...

微信恢复好友怎么弄回来(vx好友恢复)
  • 微信恢复好友怎么弄回来(vx好友恢复)
  • 微信恢复好友怎么弄回来(vx好友恢复)
  • 微信恢复好友怎么弄回来(vx好友恢复)
  • 微信恢复好友怎么弄回来(vx好友恢复)
u盘检测软件下载(u盘测试软件)

1、u盘芯片检测工具(ChipEasy)可以查看USB设备PID、VID、SN、制造商、产品名等;2、查看USB设备主控芯片信息、闪存芯片信息、固件信息、电流控制3、SSD型号...

电脑现在什么系统最好(电脑现在用什么系统好)

WINXP好用,但过时了。VISTA不好用,没推开就夭折了。WIN8/8.1是针对触模屏设计的,如果你用的不是触摸屏平板电脑是普通电脑,使WIN8/8.1总觉着很蹩扭。新出的WIN10,功能...

取消回复欢迎 发表评论: