<div style='--en-codeblock:true;--en-blockId:NuKlRucPSGZ;--en-meta:{"title":"","lang":"Python","theme":"default","showLine":true,"lineWrap":false};box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial; margin-top: 6px;'>import re
import openpyxl
# 打开工作簿并选择工作表
workbook = openpyxl.load_workbook('example.xlsx')
worksheet = workbook.active
# 遍历每个列并设置最合适的宽度
for col in worksheet.columns:
max_length = max([
len(str(cell.value)) + 0.7 * len(re.findall(r'([\u4e00-\u9fa5])', str(cell.value)))
for cell in col
])
worksheet.column_dimensions[col[0].column_letter].width = (max_length + 2) * 1.2
# 保存工作簿
workbook.save('example.xlsx')</div>
<div style='--en-codeblock:true;--en-blockId:3EBITaeEAlF;--en-meta:{"title":"","lang":"Python","theme":"default","showLine":true,"lineWrap":false};box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial; margin-top: 6px;'>from openpyxl import load_workbook
</div>
<div style='--en-codeblock:true;--en-blockId:_wr8TijLLqq;--en-meta:{"title":"","lang":"Python","theme":"default","showLine":true,"lineWrap":false};box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial; margin-top: 6px;'>workbook = load_workbook(filename = "./data.xlsx")
workbook.create_sheet("新创建的工作表sheet")
print(workbook.sheetnames)
workbook.save(filename = "./new_data.xlsx")
</div>
<div style='--en-codeblock:true;--en-blockId:hq5HQGSoGW5;--en-meta:{"title":"","lang":"Python","theme":"default","showLine":true,"lineWrap":false};box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial; margin-top: 6px;'>workbook.remove(workbook['新创建的工作表sheet']) # 将新创建的工作表删除
</div>
<div style='--en-codeblock:true;--en-blockId:3OooQWM16u1;--en-meta:{"title":"","lang":"Python","theme":"default","showLine":true,"lineWrap":false};box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial; margin-top: 6px;'>workbook = load_workbook(filename = "./data.xlsx") # 加载excel文件
sheet = workbook['Sheet1'] # 获取Sheet1工作表对象
workbook.copy_worksheet(sheet) # 复制这个工作表到excel文件对象
workbook.save(filename = "./new_data.xlsx") # 将该文件文件重新保存到另外一个文件</div>
<div style='--en-codeblock:true;--en-blockId:kMonSuW_JXI;--en-meta:{"title":"","lang":"Python","theme":"default","showLine":true,"lineWrap":false};box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial; margin-top: 6px;'>workbook = load_workbook(filename = "./data.xlsx") # 加载excel文件
sheet = workbook['Sheet1'] # 获取工作表对象
cell = sheet["A1"] # 获取单元格对象
cell.value = 'Python 集中营' # 向单元格写入数据
workbook.save(filename = "./new_data.xlsx") # 将修改后的excel文件对象另存为新的文件
</div>
<div style='--en-codeblock:true;--en-blockId:FQ2mR2AqkET;--en-meta:{"title":"","lang":"Python","theme":"default","showLine":true,"lineWrap":false};box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial; margin-top: 6px;'>'''
append(row) 将行数据追加到已有excel数据表的后面
row:行数据对象
'''
row_datas = [
['Python 集中营','原创文章:167篇','注册时间:2020-04-01'],
['Python 集中营','原创文章:167篇','注册时间:2020-04-01']
]
for row_data in row_datas: # 遍历准备好的数据
sheet.append(row_data) # 将每行数据加入到sheet工作表中
</div>
<div style='--en-codeblock:true;--en-blockId:uZbJTCWSAIN;--en-meta:{"title":"","lang":"Python","theme":"default","showLine":true,"lineWrap":false};box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial; margin-top: 6px;'>'''
insert_cols(idx=数字编号, amount=要插入的列数) 在idx的左边插入空列
insert_rows(idx=数字编号, amount=要插入的行数) 在idx的下边插入空行
'''
sheet.insert_cols(idx=1,amount=10) # 在第一列的左边插入十个空列
sheet.insert_rows(idx=2,amount=10) # 在第二行的下边插入十个空行
</div>
<div style='--en-codeblock:true;--en-blockId:eIvTQqnZBTO;--en-meta:{"title":"","lang":"Python","theme":"default","showLine":true,"lineWrap":false};box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial; margin-top: 6px;'>'''
delete_cols(idx=数字编号) 删除第几列
delete_rows(idx=数字编号) 删除第几行
'''
sheet.delete_cols(idx=10) # 删除第十列
sheet.delete_rows(idx=10) # 删除第十行
</div>
<div style='--en-codeblock:true;--en-blockId:zKrXRuK2i28;--en-meta:{"title":"","lang":"Python","theme":"default","showLine":true,"lineWrap":false};box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial; margin-top: 6px;'>'''
sheet.move_range("数据域",rows=数字编号,cols=数字编号)
'''
sheet.move_range("A1:C2",rows=1,cols=2) # 从A1:C2的数据域向下移动一行、向左移动两列,如果是负数则向相反的方向移动</div>
<div style='--en-codeblock:true;--en-blockId:Uqf-QGenzBB;--en-meta:{"title":"","lang":"Python","theme":"default","showLine":true,"lineWrap":false};box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial; margin-top: 6px;'>import os
from openpyxl import load_workbook
from openpyxl.drawing.image import Image
# excelPath :Excel文件的路径
# sheetName :Excel文件中要操作的sheet名称
# picPathColunmNumber :图片全路径所在的列索引[从1开始](列索引1、2、3、4...)
# writeColunmName :图片要插入的列名(列名:A、B、C、D...)
# imgWidth :图片宽度
# imgHight :图片高度
# columnWidth :图片列宽度
# rowHight :每行高度
# 插入图片
def addImgToExcel(excelPath, sheetName, picPathColunmNumber, writeColunmName, imgWidth, imgHight, columnWidth,
rowHight):
# 加载Excel文件并读取指定Sheet
wb = load_workbook(excelPath)
ws = wb[sheetName]
# 获取整个sheet的最大行数
Max_RowNumber = ws.max_row
# 从表格第二行开始插入图片
for rowid in range(2,Max_RowNumber+1):
# 设置行高(除去第一行)
ws.row_dimensions[rowid].height = rowHight
# 取到第N行第N列的值(图片的全路径)
# picPath = "./image/B00EVB04NC.jpg"
picPath = ws.cell(rowid, picPathColunmNumber).value
# 对得到的路径进行判断
if picPath and os.path.exists(picPath):
# 设置图片尺寸大小
img = Image(picPath)
img.width = imgWidth
img.height = imgHight
# 写入图片
ws.add_image(img, str(writeColunmName) + str(rowid))
# 列宽
ws.column_dimensions[writeColunmName].width = columnWidth
print(f"插入图片成功,i= {rowid},剩余{1751-rowid}个")
else:
print("插入图片失败")
continue
wb.save(excelPath)
# 方法入口
if __name__ == '__main__':
addImgToExcel('0616_3.xlsx', 'demo', 1, 'B', 65, 71, 8, 55)</div>
💬 评论交流
这个技巧很实用,感谢分享!