GPT带我学Openpyxl操作Excel

注:以下文字大部分文字和代码由GPT生成

一、openpyxl详细介绍

Openpyxl是一个用于读取和编写Excel 2010 xlsx/xlsm/xltx/xltm文件的Python库。它允许您使用Python操作Excel文件,包括创建新的工作簿、读取和修改现有工作簿中的数据、设置单元格格式以及编写公式。Openpyxl提供了丰富的功能,包括对工作表、单元格、图表和样式的操作,使得处理Excel文件变得简单而高效。

二、基本操作

2.1 openpyxl 修改字体

python 复制代码
from openpyxl import load_workbook
from openpyxl.styles import Font, Alignment

# Load the workbook
workbook = load_workbook('your_file.xlsx')
sheet = workbook.active

# Apply font and alignment to all cells
for row in sheet.iter_rows():
    for cell in row:
        cell.font = Font(name='Arial', size=12, bold=True)
        cell.alignment = Alignment(horizontal='center', vertical='center')

# Save the workbook
workbook.save('your_file.xlsx')

2.2 openpyxl 加边框

python 复制代码
from openpyxl import load_workbook
from openpyxl.styles import Border, Side

# Load the workbook
workbook = load_workbook('your_file.xlsx')
sheet = workbook.active

# Create a border style
border_style = Border(left=Side(style='thin'), 
                      right=Side(style='thin'), 
                      top=Side(style='thin'), 
                      bottom=Side(style='thin'))

# Apply border to all cells
for row in sheet.iter_rows():
    for cell in row:
        cell.border = border_style

# Save the workbook
workbook.save('your_file.xlsx')

2.3 openpyxl 文字居中

python 复制代码
from openpyxl import load_workbook
from openpyxl.styles import Alignment

# Load the workbook
workbook = load_workbook('your_file.xlsx')
sheet = workbook.active

# Apply center alignment to all cells
for row in sheet.iter_rows():
    for cell in row:
        cell.alignment = Alignment(horizontal='center', vertical='center')

# Save the workbook
workbook.save('your_file.xlsx')

2.4 openpyxl 调整列宽

python 复制代码
from openpyxl import load_workbook

# Load the workbook
workbook = load_workbook('your_file.xlsx')
sheet = workbook.active

# Adjust column widths
sheet.column_dimensions['A'].width = 20  # Adjust the width of column A to 20
sheet.column_dimensions['B'].width = 30  # Adjust the width of column B to 30

# Save the workbook
workbook.save('your_file.xlsx')

2.5 openpyxl 数字只显示小数点后4位

python 复制代码
from openpyxl import load_workbook

# Load the workbook
workbook = load_workbook('your_file.xlsx')
sheet = workbook.active

# Set the number format to display only four decimal places
for row in sheet.iter_rows():
    for cell in row:
        cell.number_format = '0.0000'  # Display only four decimal places

# Save the workbook
workbook.save('your_file.xlsx')

2.6 openpyxl 改变背景色

python 复制代码
from openpyxl import load_workbook
from openpyxl.styles import PatternFill

# Load the workbook
workbook = load_workbook('your_file.xlsx')
sheet = workbook.active

# Set the background color to green for all cells
green_fill = PatternFill(start_color='00FF00', end_color='00FF00', fill_type='solid')
for row in sheet.iter_rows():
    for cell in row:
        cell.fill = green_fill

# Save the workbook
workbook.save('your_file.xlsx')

2.7 openpyxl 读取值某行某列值

python 复制代码
from openpyxl import load_workbook

# Load the workbook
workbook = load_workbook('your_file.xlsx')
sheet = workbook.active

# Read the value of a specific cell
value = sheet.cell(row=1, column=1).value  # Replace row and column with the desired cell coordinates

# Print the value
print(value)

2.8 openpyxl 写入某行某列值

python 复制代码
from openpyxl import load_workbook

# Load the workbook
workbook = load_workbook('your_file.xlsx')
sheet = workbook.active

# Write a value to a specific cell
sheet.cell(row=1, column=1, value='Hello, World!')  # Replace row and column with the desired cell coordinates

# Save the workbook
workbook.save('your_file.xlsx')

2.9 openpyxl 设置文字颜色

python 复制代码
from openpyxl import load_workbook
from openpyxl.styles import Font

# Load the workbook
workbook = load_workbook('your_file.xlsx')
sheet = workbook.active

# Set the text color of a specific cell
cell = sheet.cell(row=1, column=1)  # Replace row and column with the desired cell coordinates
cell.value = 'Hello, World!'
cell.font = Font(color="FF0000")  # Set the text color to red

# Save the workbook
workbook.save('your_file.xlsx')

2.10 openpyxl设置公式

直接写入公式字符串即可,例如=AVERAGE(D18:D33) ,但是表格的列需要转换为字母表达

python 复制代码
# 使用以下代码将列数转换为字母
def num_to_col_letters(num):
    letters = ""
    while num > 0:
        num, remainder = divmod(num - 1, 26)
        letters = chr(65 + remainder) + letters
    return letters

三、综合效果

以上gpt生成的代码都验证通过,最后加粗、加边框、加颜色、居中实现效果如下:

相关推荐
Python大数据分析@17 分钟前
python操作CSV和excel,如何来做?
开发语言·python·excel
John.liu_Test1 小时前
js下载excel示例demo
前端·javascript·excel
ruleslol3 小时前
VBA02-初识宏——EXCEL录像机
excel·vba
IT铺子3 小时前
制定Excel使用规范和指导,提升数据处理的效率和准确性,减少错误和数据丢失的风险
excel
是萝卜干呀3 小时前
Backend - Python 爬取网页数据并保存在Excel文件中
python·excel·table·xlwt·爬取网页数据
光芒再现dev8 小时前
已解决,部署GPTSoVITS报错‘AsyncRequest‘ object has no attribute ‘_json_response_data‘
运维·python·gpt·语言模型·自然语言处理
神奇夜光杯9 小时前
Python酷库之旅-第三方库Pandas(202)
开发语言·人工智能·python·excel·pandas·标准库及第三方库·学习与成长
小c君tt10 小时前
MFC中Excel的导入以及使用步骤
c++·excel·mfc
一名技术极客12 小时前
Vue2 doc、excel、pdf、ppt、txt、图片以及视频等在线预览
pdf·powerpoint·excel·文件在线预览
用余生去守护12 小时前
【反射率】-- Lab 转换(excel)
excel