利用Python实现添加或读取Excel公式

2025-03-20 01:50

本文主要是介绍利用Python实现添加或读取Excel公式,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

《利用Python实现添加或读取Excel公式》Excel公式是数据处理的核心工具,从简单的加减运算到复杂的逻辑判断,掌握基础语法是高效工作的起点,下面我们就来看看如何使用Python进行Excel公...

Excel公式是数据处理的核心工具。从简单的加减运算到复杂的逻辑判断,掌握基础语法是高效工作的起点。例如使用SUM函数快速求和,或通过IF函数实现条件判断。通过公式计算数据能减少人工计算的错误率。本文将介绍如何通过Python在Excel中添加各种公式/函数、或者读取Excel中的公式。

Python Excel 库安装

要在Python应用程序中操作Excel文档,需要用到Spire.XLS for Python库。可以直接使用以下pip命令安装:

pip install Spire.XLS

Python 在 Excel 中添加公式/函数

Spire.XLS for Python 提供的 Worksheet.Range[].Formula 属性可用于为 Excel 工作表中的特定单元格添加公式。支www.chinasem.cn持添加多种常见公式如 SUM、AVERAGE、COUNT、IF等,此外还支持日期和时间公式、数学和三角函数等。

步骤如下:

  • 创建一个Excel工作簿。
  • 通过 Workbook.Worksheets[sheetIndex] 属性获取指定工作表。
  • 通过 Worksheet.Range[rowIndex, columnIndex].Text 和 Worksheet.Range[rowIndex, columnIndex].NumberValue 属性在指定单元格中添加文本和数字数据。
  • 通过 Worksheet.Range[rowIndex, columnIndex].Formula 属性在指定单元格中添加公式。
  • 保存结果文件。

Python代码:

from spire.xls import *
from spire.xls.common import *

# 创建工作簿
workbook = Workbook()

# 获取第一张工作表
sheet = workbook.Worksheets[0]

# 定义两个变量
currentRow = 1
currentFormula = ""

# 在单元格中添加文本并设置单元格样式
sheet.Range[currentRow, 1].Text = "测试数据:"
sheet.Range[currentRow, 1].Style.Font.IsBold = True
sheet.Range[currentRow, 1].Style.FillPattern = ExcelPatternType.Solid
sheet.Range[currentRow, 1].Style.KnownColor = ExcelColors.LightGreen1
sheet.Range[currentRow, 1].Style.Borders[BordersLineType.EdgeBottom].LineStyle = LineStyleType.Medium
currentRow += 1

# 在单元格中添加数据
sheet.Range[currentRow, 1].NumberValue = 7.3
sheet.Range[currentRow, 2].NumberValue = 5
sheet.Range[currentRow, 3].NumberValue = 8.2
sheet.Range[currentRow, 4].NumberValue = 4
sheet.Range[currentRow, 5].NumberValue = 3
sheet.Range[currentRow, 6].NumberValue = 11.3
currentRow += 2

# 在单元格中添加文本并设置单元格样式
sheet.Range[currentRow, 1].Text = "公式"
sheet.Range[currentRow, 2].Text = "计算结果"
sheet.Range[currentRow, 1, currentRow, 2].Style.Font.IsBold = True
sheet.Range[currentRow, 1, currentRow, 2].Style.KnownColor = ExcelColors.LightGreen1
sheet.Range[currentRow, 1, currentRow, 2].Style.FillPattern = ExcelPatternType.Solid
sheet.Range[currentRow, 1, currentRow, 2].Style.Borders[BordersLineType.EdgeBottom].LineStyle = LineStyleType.Medium
currentRow += 1

# 添加表达式
currentFormula = "=1+2+3+4+5-6-7+8-9"
sheet.Range[currentRow, 1].Text = "'" + currentFormula
sheet.Range[currentRow, 2].Formula = currentFormula
currentRow += 1

currentFormula = "=33*3/4-2+10"
sheet.Range[currentRow, 1].Text = "'" + currentFormula
sheet.Range[currentRow, 2].Formula = currentFormula
currentRow += 1

# 添加单元格引用
currentFormula = "=Sheet1!$B$2"
sheet.Range[currentRow, 1].Text = "'" + currentFormula
sheet.Range[currentRow, 2].Formula = currentFormula
currentRow += 1

# 添加AVERAGE函数,用于计算一组数值的平均值
currentFormula = "=AVERAGE(Sheet1!$D$2:F$2)"
sheet.Range[currentRow, 1].Text = "'" + currentFormula
sheet.Range[currentRow, 2].Formula = currentFormula
currentRow += 1

# 添加SUM函数,对一组数值进行求和计算
currentFormula = "=SUM(18,29)"
sheet.Range[currentRow, 1].Text = "'" + currentFormula
sheet.Range[currentRow, 2].Formula = currentFormula
currentRow += 1

# 添加IF函数,用于根据指定的条件进行判断,并返回不同的结果
currentFormula = "=IF(4,2,2)"
sheet.Range[currentRow, 1].Text = "'" + currentFormula
sheet.Range[currentRow, 2].Formula = currentFormula
currentRow += 1

# 添加COUNT计数,用于统计包含数字的单元格个数
currentFormula = "=COUNT(3,5,8,10,2,34)"
sheet.Range[currentRow, 1].Text = "'" + currentFormula
sheet.Range[currentRow, 2].Formula = currentFormula
currentRow += 1

# 添加SUBTOTAL函数,用于在数据列表或数据库中进行分类汇总
currentFormula = "=SUBTOTAL(3,Sheet1!A2:F2)"
sheet.Range[currentRow, 1].Text = "'" + currentFormula
sheet.Range[currentRow, 2].Formula = currentFormula
currentRow += 1

# 添加NOW函数,用于返回当前的日期
currentFormula = "=NOW()"
sheet.Range[currentRow, 1].Text = "'" + currentFormula
sheet.Range[currentRow, 2].Formula = currentFormula
sheet.Range[currentRow, 2].Style.NumberFormat = "yyyy-phpMM-DD"
currentRow += 1

# 添加SECOND函数,用于从时间值中提取秒数
currentFormula = "=SECOND(0.503)"
sheet.Range[currentRow, 1].Text = "'" + currentFormula
sheet.Range[currentRow, 2].Formula = currentFormula
currentRow += 1

# 添加MINUTE函数,用于从时间值里提取分钟数
currentFormula = "=MINUTE(0.78125)"
sheet.Range[currentRow, 1].Text = "'" + currentFormula
sheet.Range[currentRow, 2].Formula = currentFormula
currentRow += 1

# 添加MONTH函数,用于从日期值中提取月份信息
currentFormuphpla = "=MONTH(9)"
sheet.Range[currentRow, 1].Text = "'" + currentFormula
sheet.Range[currentRow, 2].Formula = currentFormula
currentRow += 1

# 添加DAY函数,用于从日期值中提取出具体的日信息
currentFormula = "=DAY(10)"
sheet.Range[currentRow, 1].Text = "'" + currentFormula
sheet.Range[currentRow, 2].Formula = currentFormula
currentRow += 1

# 添加TIME函数,通过分别指定小时、分钟和秒来创建一个标准的时间格式
currentFormula = "=TIME(4,5,7)"
sheet.Range[currentRow, 1].Text = "'" + currentFormula
sheet.Range[currentRow, 2].Formula = currentFormula
currentRow += 1

# 添加DATE函数,用于根据指定的年、月、日构建一个日期。
currentFormula = "=China编程DATE(6,4,2)"
sheet.Range[currentRow, 1].Text = "'" + currentFormula
sheet.Range[currentRow, 2].Formula = currentFormula
currentRow += 1

# 添加RAND函数,用于生成一个大于等于 0 且小于 1 的随机小数
currentFormula = "=RAND()"
sheet.Range[currentRow, 1].Text =www.chinasem.cn "'" + currentFormula
sheet.Range[currentRow, 2].Formula = currentFormula
currentRow += 1

# 添加HOUR函数,用于从时间值中提取小时数
currentFormula = "=HOUR(0.5)"
sheet.Range[currentRow, 1].Text = "'" + currentFormula
sheet.Range[currentRow, 2].Formula = currentFormula
currentRow += 1

# 添加MOD函数,用于返回两数相除的余数
currentFormula = "=MOD(5,3)"
sheet.Range[currentRow, 1].Text = "'" + currentFormula
sheet.Range[currentRow, 2].Formula = currentFormula
currentRow += 1

# 添加WEEKDAY函数,用于返回某个日期对应的星期数
currentFormula = "=WEEKDAY(3)"
sheet.Range[currentRow, 1].Text = "'" + currentFormula
sheet.Range[currentRow, 2].Formula = currentFormula
currentRow += 1

# 添加YEAR函数,用于从给定的日期中提取出对应的年份
currentFormula = "=YEAR(23)"
sheet.Range[currentRow, 1].Text = "'" + currentFormula
sheet.Range[currentRow, 2].Formula = currentFormula
currentRow += 1

# 添加NOT函数,用于对给定的逻辑值取反
currentFormula = "=NOT(true)"
sheet.Range[currentRow, 1].Text = "'" + currentFormula
sheet.Range[currentRow, 2].Formula = currentFormula
currentRow += 1

# 添加OR函数,用于对多个条件进行逻辑或运算(当给定的条件中至少有一个为 TRUE 时,函数就会返回 TRUE;只有当所有条件都为 FALSE 时,函数才会返回 FALSE。)
currentFormula = "=OR(true)"
sheet.Range[currentRow, 1].Text = "'" + currentFormula
sheet.Range[currentRow, 2].Formula = currentFormula
currentRow += 1

# 添加AND函数,用于对多个条件进行逻辑与运算(只有当所有指定的条件都为 TRUE 时,AND 函数才会返回 TRUE;只要有一个条件为 FALSE,函数就会返回 FALSE。)
currentFormula = "=AND(TRUE)"
sheet.Range[currentRow, 1].Text = "'" + currentFormula
sheet.Range[currentRow, 2].Formula = currentFormula
currentRow += 1

# 添加VALUE函数,用于将文本形式的数字转换为数值类型
currentFormula = "=VALUE(30)"
sheet.Range[currentRow, 1].Text = "'" + currentFormula
sheet.Range[currentRow, 2].Formula = currentFormula
currentRow += 1

# 添加LEN函数,用于返回文本字符串中的字符个数
currentFormula = "=LEN(\"world\")"
sheet.Range[currentRow, 1].Text = "'" + currentFormula
sheet.Range[currentRow, 2].Formula = currentFormula
currentRow += 1

# 添加MID函数,用于从一个文本字符串中指定的起始位置开始,提取指定长度的字符
currentFormula = "=MID(\"world\",4,2)"
sheet.Range[currentRow, 1].Text = "'" + currentFormula
sheet.Range[currentRow, 2].Formula = currentFormula
currentRow += 1

# 添加ROUND函数,用于按指定的位数对数值进行四舍五入
currentFormula = "=ROUND(7,3)"
sheet.Range[currentRow, 1].Text = "'" + currentFormula
sheet.Range[currentRow, 2].Formula = currentFormula
currentRow += 1

# 添加SIGN函数,用于判断一个数值的正负性,并返回其符号对应的数值
currentFormula = "=SIGN(4)"
sheet.Range[currentRow, 1].Text = "'" + currentFormula
sheet.Range[currentRow, 2].Formula = currentFormula
currentRow += 1

# 添加INT函数,用于将一个数值向下取整为最接近的整数,也就是去除数值的小数部分,返回不大于该数值的最大整数。
currentFormula = "=INT(200)"
sheet.Range[currentRow, 1].Text = "'" + currentFormula
sheet.Range[currentRow, 2].Formula = currentFormula
currentRow += 1

# 添加ABS函数,用于返回一个数的绝对值,也就是将该数的负号去除,只保留其数值大小,不考虑其正负性。
currentFormula = "=ABS(-1.21)"
sheet.Range[currentRow, 1].Text = "'" + currentFormula
sheet.Range[currentRow, 2].Formula = currentFormula
currentRow += 1

# 添加LN函数,用于计算一个数的自然对数。
currentFormula = "=LN(15)"
sheet.Range[currentRow, 1].Text = "'" + currentFormula
sheet.Range[currentRow, 2].Formula = currentFormula
currentRow += 1

# 添加EXP函数,用于计算自然常数 e(约等于 2.71828)的指定次幂
currentFormula = "=EXP(20)"
sheet.Range[currentRow, 1].Text = "'" + currentFormula
sheet.Range[currentRow, 2].Formula = currentFormula
currentRow += 1

# 添加SQRT函数,用于计算一个数的算术平方根
currentFormula = "=SQRT(40)"
sheet.Range[currentRow, 1].Text = "'" + currentFormula
sheet.Range[currentRow, 2].Formula = currentFormula
currentRow += 1

# 添加PI函数,返回数学常数 (圆周率)的近似值
currentFormula = "=PI()"
sheet.Range[currentRow, 1].Text = "'" + currentFormula
sheet.Range[currentRow, 2].Formula = currentFormula
currentRow += 1

# 添加COS函数,用于计算一个角度的余弦值
currentFormula = "=COS(9)"
sheet.Range[currentRow, 1].Text = "'" + currentFormula
sheet.Range[currentRow, 2].Formula = currentFormula
currentRow += 1

# 添加SIN函数,用于计算给定角度的正弦值
currentFormula = "=SIN(45)"
sheet.Range[currentRow, 1].Text = "'" + currentFormula
sheet.Range[currentRow, 2].Formula = currentFormula
currentRow += 1

# 添加MAX函数,用于返回一组数值中的最大值
currentFormula = "=MAX(10,30)"
sheet.Range[currentRow, 1].Text = "'" + currentFormula
sheet.Range[currentRow, 2].Formula = currentFormula
currentRow += 1

# 添加MIN函数,用于返回一组数值中的最小值
currentFormula = "=MIN(5,7)"
sheet.Range[currentRow, 1].Text = "'" + currentFormula
sheet.Range[currentRow, 2].Formula = currentFormula
currentRow += 1

# 设置列宽
sheet.SetColumnWidth(1, 32)
sheet.SetColumnWidth(2, 16)
sheet.SetColumnWidth(3, 16)

# 应用样式
style = workbook.Styles.Add("Style")
style.HorizontalAlignment = HorizontalAlignType.Left
sheet.ApplyStyle(style)

# 保存生成文档
workbook.SaveToFile("Excel公式.xlsx", ExcelVersion.Version2016)
workbook.Dispose()

生成结果:

利用Python实现添加或读取Excel公式

Python 读取 Excel 中的公式/函数

我们可以遍历工作表中的所有单元格,然后通过 Cell.HasFormula 属性找到包含公式的单元格,再使用 CellRange.Formula 属性获取单元格的公式。

步骤如下:

  • 加载 Excel 文件。
  • 通过 Workbook.Worksheets[sheetIndex] 属性获取指定工作表。
  • 通过 Workheet.AllocatedRange 属性获取工作表的使用范围。
  • 创建一个空列表。
  • 遍历使用范围内的所有单元格。
  • 通过 Cell.HasFormula 属性查找包含公式的单元格。
  • 使用 CellRange.RangeAddressLocal 和 CellRange.Formula 属性获取单元格的名称和公式。
  • 将读取内容添加到列表中,然后写入txt文本文件。

Python代码:

from spire.xls import *
from spire.xls.common import *

# 加载Excel文档
workbook = Workbook()
workbook.LoadFromFile("Excel公式.xlsx")

# 获取第一张工作表
sheet = workbook.Worksheets[0]

# 获取工作表的使用范围
usedRange = sheet.AllocatedRange

# 创建列表
list = []

# 遍历工作表使用范围内的单元格
for cell in usedRange:
    # 检查单元格是否有公式
    if(cell.HasFormula):
        # 获取单元格名称
        cellName = cell.RangeAddressLocal
        # 获取公式
        formula = cell.Formula
        # 将单元格名称和公式添加到列表中
        list.append(cellName + " 公式为: " + formula)

# 导入txt文本文件
with open("读取公式.txt", "w", encoding = "utf-8") as text_file:
    for item in list:
        text_file.write(item + "\n")

workbook.Dispose()

读取结果:

利用Python实现添加或读取Excel公式

以上就是利用Python实现添加或读取Excel公式的详细内容,更多关于Python Excel公式的资料请关注编程China编程(www.chinasem.cn)其它相关文章!

这篇关于利用Python实现添加或读取Excel公式的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1153844

相关文章

使用Java将各种数据写入Excel表格的操作示例

《使用Java将各种数据写入Excel表格的操作示例》在数据处理与管理领域,Excel凭借其强大的功能和广泛的应用,成为了数据存储与展示的重要工具,在Java开发过程中,常常需要将不同类型的数据,本文... 目录前言安装免费Java库1. 写入文本、或数值到 Excel单元格2. 写入数组到 Excel表格

Python中pywin32 常用窗口操作的实现

《Python中pywin32常用窗口操作的实现》本文主要介绍了Python中pywin32常用窗口操作的实现,pywin32主要的作用是供Python开发者快速调用WindowsAPI的一个... 目录获取窗口句柄获取最前端窗口句柄获取指定坐标处的窗口根据窗口的完整标题匹配获取句柄根据窗口的类别匹配获取句

利用Python打造一个Excel记账模板

《利用Python打造一个Excel记账模板》这篇文章主要为大家详细介绍了如何使用Python打造一个超实用的Excel记账模板,可以帮助大家高效管理财务,迈向财富自由之路,感兴趣的小伙伴快跟随小编一... 目录设置预算百分比超支标红预警记账模板功能介绍基础记账预算管理可视化分析摸鱼时间理财法碎片时间利用财

在 Spring Boot 中实现异常处理最佳实践

《在SpringBoot中实现异常处理最佳实践》本文介绍如何在SpringBoot中实现异常处理,涵盖核心概念、实现方法、与先前查询的集成、性能分析、常见问题和最佳实践,感兴趣的朋友一起看看吧... 目录一、Spring Boot 异常处理的背景与核心概念1.1 为什么需要异常处理?1.2 Spring B

Python中的Walrus运算符分析示例详解

《Python中的Walrus运算符分析示例详解》Python中的Walrus运算符(:=)是Python3.8引入的一个新特性,允许在表达式中同时赋值和返回值,它的核心作用是减少重复计算,提升代码简... 目录1. 在循环中避免重复计算2. 在条件判断中同时赋值变量3. 在列表推导式或字典推导式中简化逻辑

python处理带有时区的日期和时间数据

《python处理带有时区的日期和时间数据》这篇文章主要为大家详细介绍了如何在Python中使用pytz库处理时区信息,包括获取当前UTC时间,转换为特定时区等,有需要的小伙伴可以参考一下... 目录时区基本信息python datetime使用timezonepandas处理时区数据知识延展时区基本信息

Python位移操作和位运算的实现示例

《Python位移操作和位运算的实现示例》本文主要介绍了Python位移操作和位运算的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一... 目录1. 位移操作1.1 左移操作 (<<)1.2 右移操作 (>>)注意事项:2. 位运算2.1

如何在 Spring Boot 中实现 FreeMarker 模板

《如何在SpringBoot中实现FreeMarker模板》FreeMarker是一种功能强大、轻量级的模板引擎,用于在Java应用中生成动态文本输出(如HTML、XML、邮件内容等),本文... 目录什么是 FreeMarker 模板?在 Spring Boot 中实现 FreeMarker 模板1. 环

Qt实现网络数据解析的方法总结

《Qt实现网络数据解析的方法总结》在Qt中解析网络数据通常涉及接收原始字节流,并将其转换为有意义的应用层数据,这篇文章为大家介绍了详细步骤和示例,感兴趣的小伙伴可以了解下... 目录1. 网络数据接收2. 缓冲区管理(处理粘包/拆包)3. 常见数据格式解析3.1 jsON解析3.2 XML解析3.3 自定义

使用Python和Pyecharts创建交互式地图

《使用Python和Pyecharts创建交互式地图》在数据可视化领域,创建交互式地图是一种强大的方式,可以使受众能够以引人入胜且信息丰富的方式探索地理数据,下面我们看看如何使用Python和Pyec... 目录简介Pyecharts 简介创建上海地图代码说明运行结果总结简介在数据可视化领域,创建交互式地