当前位置: 首页 > news >正文

Python 之 Excel 表格常用操作

示例文件 test.xlsx

   

将各个表单拆分成单独的 Excel 文件

import os.pathimport openpyxl
import pandasdef handle_excel(file_path):dirname = os.path.dirname(file_path)basename = os.path.basename(file_path).split(".")[0]wb = openpyxl.load_workbook(file_path)sheet_names = wb.sheetnamesprint(sheet_names)for sheet_name in sheet_names:sheet_info = pandas.read_excel(file_path, dtype='str', sheet_name=sheet_name)new_file_path = os.path.join(dirname, f"{basename}_{sheet_name}.xlsx")print(new_file_path)sheet_info.to_excel(new_file_path, index=False)if __name__ == '__main__':file_path = os.path.join(os.getcwd(), "test.xlsx")handle_excel(file_path)
['Sheet1', 'Sheet2']
E:\lky_project\tmp_project\test_project\test_Sheet1.xlsx
E:\lky_project\tmp_project\test_project\test_Sheet2.xlsx

数据分组后按分组结果生成多个 Excel

import os.pathimport openpyxl
import pandasdef handle_excel(file_path):dirname = os.path.dirname(file_path)basename = os.path.basename(file_path).split(".")[0]wb = openpyxl.load_workbook(file_path)sheet_names = wb.sheetnamesprint(sheet_names)sheet_name = sheet_names[1]sheet_info = pandas.read_excel(file_path, dtype='str', sheet_name=sheet_name)group_info = sheet_info.groupby("省份")for key, value in group_info:print(key, value)new_file_path = os.path.join(dirname, f"{basename}_{sheet_name}_{key}.xlsx")print(new_file_path)value.to_excel(new_file_path, index=False)if __name__ == '__main__':file_path = os.path.join(os.getcwd(), "test.xlsx")handle_excel(file_path)
['Sheet1', 'Sheet2']
四川序号  省份 月份  金额
0  1  四川  1  10
1  2  四川  2  20
E:\lky_project\tmp_project\test_project\test_Sheet2_四川.xlsx
陕西序号  省份 月份  金额
2  3  陕西  1  30
E:\lky_project\tmp_project\test_project\test_Sheet2_陕西.xlsx

对 Excel 有效使用区域进行截图保存

import os.path
import xlwings
from PIL import ImageGrab, Image
from xlwings._xlwindows import COMRetryObjectWrapper, App
from win32com.client import DispatchExdef handle_excel(file_path):_xl = COMRetryObjectWrapper(DispatchEx("ket.Application"))impl = App(visible=False, add_book=False, xl=_xl)app = xlwings.App(visible=False, add_book=False, impl=impl)  # 如果运行中不想看到打开 Excel 的操作,设置 visible 为 Falsewb = app.books.open(file_path)sheet = wb.sheets["Sheet1"]all = sheet.used_range  # 获取表格数据使用范围# all = sheet.range("Sheet1!$A$1:$E$4")  # 带表单名称# all = sheet.range("$A$1:$E$4")  # 也可以自定义数据范围,通过对角元素的坐标进行范围限定print(all)all.api.CopyPicture()  # 复制使用范围sheet.api.Paste()  # 粘贴pic = sheet.pictures[0]  # 获取当前图片pic.api.Copy()  # 复制图片到剪切板img = ImageGrab.grabclipboard()  # 获取剪切板的图片数据x, y = img.sizep = Image.new('RGBA', img.size, (255, 255, 255))  # 重新设置背景颜色,不然背景是透明的p.paste(img, (0, 0, x, y), img)  # 将截图粘贴到图片对象p.save("test.png")  # 图片保存pic.delete()  # 删除 sheet 表单粘贴的图片,避免截图影响 Excel 原始数据# wb.save()  # 保存退出wb.close()app.quit()if __name__ == '__main__':file_path = os.path.join(os.getcwd(), "test_Sheet2_四川.xlsx")handle_excel(file_path)

当然,也可以自定义数据截图范围。 

上传文件自动选择

这个和 Excel 没有关系,夹带的私货。

在打开的 windows 窗口自动选择文件并确认

import os.path
import time
import win32con
import win32gui# 自动选择文件并确认
def file_upload(file):retry_times = 3while retry_times > 0:time.sleep(3)dialog = win32gui.FindWindow('#32770', '打开')if dialog:breakretry_times -= 1time.sleep(3)ComboBoxEx32 = win32gui.FindWindowEx(dialog, 0, 'ComboBoxEx32', None)ComboBox = win32gui.FindWindowEx(ComboBoxEx32, 0, 'ComboBox', None)Edit = win32gui.FindWindowEx(ComboBox, 0, 'Edit', None)Button = win32gui.FindWindowEx(dialog, 0, 'Button', None)win32gui.SendMessage(Edit, win32con.WM_SETTEXT, None, file)time.sleep(1)win32gui.SendMessage(dialog, win32con.WM_COMMAND, 1, Button)time.sleep(1)return Trueif __name__ == '__main__':file = os.path.join(os.getcwd(), "test.txt")print(file)file_upload(file)

pip 本地安装依赖包出现 ERROR: No matching distribution found for 报错时:

pip install --no-build-isolation --no-index --find-links=./ fairscale

切换输入法为英文

import win32api
import win32con
import win32guiLANGUAGE = {'ZH': 0x0804,  # 中文(中国)"EN": 0x0409,  # 英语(美国) 美式键盘
}def change_language(language="EN"):language = LANGUAGE.get(language)hwnd = win32gui.GetForegroundWindow()win32api.SendMessage(hwnd, win32con.WM_INPUTLANGCHANGEREQUEST, 0, language)if __name__ == '__main__':change_language('EN')

切换成功以后,右下角的输入法展示会显示一个 ENG 的图标,如果你本身没有安装英文输入法的话是没办法切换的哟。

http://www.lryc.cn/news/527212.html

相关文章:

  • 2025春招 SpringCloud 面试题汇总
  • jupyter版本所引起的扩展插件问题
  • 01机器学习入门
  • 实现一个安全且高效的图片上传接口:使用ASP.NET Core和SHA256哈希
  • PyTorch中的movedim、transpose与permute
  • HTTP(1)
  • C#常考随笔2:函数中多次使用string的+=处理,为什么会产生大量内存垃圾(垃圾碎片),有什么好的方法可以解决?
  • leetcode刷题记录(一百)——121. 买卖股票的最佳时机
  • MATLAB绘图时线段颜色、数据点形状与颜色等设置,介绍
  • CIMRTS材质美化--放大采样、缩小采样
  • P8738 [蓝桥杯 2020 国 C] 天干地支
  • PyCharm接入DeepSeek实现AI编程
  • Java编程语言:辉煌的历史与未来前景
  • 麦田物语学习笔记:保存和加载场景中的物品
  • 页高速缓存与缓冲区缓存的应用差异
  • 深度学习 Pytorch 单层神经网络
  • 一文读懂 HTTP:Web 数据交换的基石
  • 算法知识补充2
  • Vue.js组件开发-实现对视频预览
  • SSM开发(三) spring与mybatis整合(含完整运行demo源码)
  • .NET MAUI进行UDP通信(二)
  • 14-6-3C++STL的list
  • AAAI2024论文解读|HGPROMPT Bridging Homogeneous and Heterogeneous Graphs
  • WPA_cli P2P命令详解及使用
  • 【竞技宝】LPL:IG3-1击败RNG
  • sqlite3 学习笔记
  • Visual Studio Community 2022(VS2022)安装方法
  • 项目集成RabbitMQ
  • 3097. 或值至少为 K 的最短子数组 II
  • Linux 35.6 + JetPack v5.1.4之编译器升级