1234

ExcelHome技术论坛

用户名  找回密码
 免费注册

QQ登录

只需一步,快速开始

快捷登录

帖子
EH技术汇-专业的职场技能充电站 妙哉!函数段子手趣味讲函数 Excel服务器-会Excel,做管理系统 效率神器,一键搞定繁琐工作
HR薪酬管理数字化实战 Excel 2021函数公式学习大典 Excel数据透视表实战秘技 打造核心竞争力的职场宝典
让更多数据处理,一键完成 数据工作者的案头书 免费直播课集锦 ExcelHome出品 - VBA代码宝免费下载
用ChatGPT与VBA一键搞定Excel WPS表格从入门到精通 Excel VBA经典代码实践指南
查看: 506|回复: 3

[转帖] Python生成二维码代码

[复制链接]

TA的精华主题

TA的得分主题

发表于 2025-1-7 22:42 | 显示全部楼层 |阅读模式

import xlwings as xw
import os
import glob
import qrcode
src_dir = os.getcwd()
files_list = glob.glob('*.xlsm')
if not files_list:
    files_list = glob.glob('*.xlsm')
if not files_list:
    print("No Excel files found.")
    exit()
excelfilepath = files_list[-1]
app = xw.App(visible=False, add_book=False)
excelbook = app.books.open(excelfilepath)
sheet = excelbook.sheets[-1]
value = sheet.range(1, 1).expand('down').value
excelbook.close()
app.quit()
def generate_qrcode(text):
    img = qrcode.make(text)
    img.save(os.path.join(src_dir, text + '.png'))
for text in value:
    generate_qrcode(text)
html_list = []
for text in value:
    html_list.append('<table><img src="{}" height="90"></table>'.format(os.path.join(src_dir, str(text) + ".png")))
with open('barcode_html.txt', 'w', encoding='utf-8') as f:
    for i in html_list:
        f.write(i + '\n')

需要把生成TXT文档里面的代码,复制到表格里面


TA的精华主题

TA的得分主题

 楼主| 发表于 2025-2-4 15:56 | 显示全部楼层
[广告] Excel易用宝 - 提升Excel的操作效率 · Excel / WPS表格插件       ★免费下载 ★       ★ 使用帮助
本机IP地址查看及获取,包括IPV6
pip install pyperclip
pip install psutil

  1. import tkinter as tk
  2. from tkinter import ttk
  3. import socket
  4. import psutil
  5. import pyperclip
  6. import subprocess
  7. from tkinter import messagebox


  8. def get_network_info():
  9.     """获取网络接口信息"""
  10.     network_info = []
  11.     addrs = psutil.net_if_addrs()
  12.     net_stats = psutil.net_if_stats()
  13.     seen_interfaces = set()

  14.     for interface in addrs.keys():
  15.         if net_stats[interface].isup and interface not in seen_interfaces:
  16.             ipv4_address, mac_address = "Not Available", "Not Available"
  17.             ipv6_addresses = []

  18.             for addr in addrs[interface]:
  19.                 if addr.family == socket.AF_INET:
  20.                     ipv4_address = addr.address
  21.                 elif addr.family == socket.AF_INET6:
  22.                     if addr.address.startswith("fe80"):
  23.                         ipv6_addresses.append(f"{addr.address} (内网可用)")
  24.                     else:
  25.                         ipv6_addresses.append(addr.address)
  26.                 elif addr.family == psutil.AF_LINK:
  27.                     mac_address = addr.address

  28.             # 将收集到的信息添加到列表中
  29.             for ipv6_addr in ipv6_addresses:
  30.                 network_info.append([interface, ipv4_address, ipv6_addr, mac_address])
  31.             seen_interfaces.add(interface)

  32.     return network_info


  33. def copy_selected_value(tree, item_id, column):
  34.     """复制选中的值并弹出提示框"""
  35.     value = tree.item(item_id, 'values')[tree['columns'].index(column)]

  36.     if column == "IPv6":
  37.         value = value.split(" (")[0]  # 去掉备注

  38.     pyperclip.copy(value)
  39.     messagebox.showinfo("提示", f"{column} '{value}' 复制成功!")


  40. def ping_ip(ip_address):
  41.     """在新CMD窗口中对指定IP进行ping操作"""
  42.     try:
  43.         subprocess.Popen(f"start cmd /k ping {ip_address}", shell=True)
  44.     except Exception as e:
  45.         messagebox.showerror("错误", f"无法 ping IP 地址: {e}")


  46. def show_context_menu(event, tree):
  47.     """显示右键上下文菜单"""
  48.     selected_item = tree.selection()
  49.     if selected_item:
  50.         column_index = int(tree.identify_column(event.x).replace("#", "")) - 1
  51.         ip_address = tree.item(selected_item[0], 'values')[column_index]

  52.         context_menu = tk.Menu(root, tearoff=0)
  53.         context_menu.add_command(label="Ping", command=lambda: ping_ip(ip_address))
  54.         context_menu.post(event.x_root, event.y_root)


  55. def on_tree_item_double_click(event, tree):
  56.     """处理双击事件以复制值"""
  57.     selected_item = tree.selection()[0]
  58.     column = tree.identify_column(event.x)
  59.     column_index = int(column.replace("#", "")) - 1
  60.     copy_selected_value(tree, selected_item, tree['columns'][column_index])


  61. def setup_treeview(frame):
  62.     """设置树形视图及其样式"""
  63.     columns = ("网络接口名称", "IPv4", "IPv6", "MAC")
  64.     tree = ttk.Treeview(frame, columns=columns, show="headings")

  65.     # 设置列标题和宽度
  66.     for col in columns:
  67.         tree.heading(col, text=col)
  68.         tree.column(col, width=200 if col == "网络接口名称" else 300, anchor='center')

  69.     style = ttk.Style()
  70.     style.configure("Treeview", rowheight=25, fieldbackground="white", borderwidth=2, relief="solid")
  71.     style.configure("Treeview.Heading", font=('Helvetica', 12, 'bold'), borderwidth=2, relief="solid")

  72.     return tree


  73. def show_network_info():
  74.     global root  # 将root设置为全局变量
  75.     root = tk.Tk()
  76.     root.title("IP 地址查看器(双击复制)")

  77.     frame = ttk.Frame(root)
  78.     frame.pack(fill=tk.BOTH, expand=True)

  79.     network_info = get_network_info()
  80.     interface_tree = setup_treeview(frame)

  81.     for info in network_info:
  82.         interface_tree.insert("", tk.END, values=info)

  83.     # 绑定事件
  84.     interface_tree.bind("<Double-1>", lambda event: on_tree_item_double_click(event, interface_tree))
  85.     interface_tree.bind("<Button-3>", lambda event: show_context_menu(event, interface_tree))

  86.     scrollbar = ttk.Scrollbar(frame, orient=tk.VERTICAL, command=interface_tree.yview)
  87.     interface_tree.configure(yscrollcommand=scrollbar.set)

  88.     interface_tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
  89.     scrollbar.pack(side=tk.RIGHT, fill=tk.Y)

  90.     # 调整窗口大小以适应内容
  91.     root.update_idletasks()
  92.     row_count = len(network_info)
  93.     root.minsize(root.winfo_width(), 25 * row_count + 100)

  94.     root.geometry("")  # 根据内容动态调整窗口大小
  95.     root.mainloop()


  96. if __name__ == "__main__":
  97.     show_network_info()
复制代码

TA的精华主题

TA的得分主题

 楼主| 发表于 2025-2-10 20:53 | 显示全部楼层
[广告] Excel易用宝 - 提升Excel的操作效率 · Excel / WPS表格插件       ★免费下载 ★       ★ 使用帮助
tk 库高分屏显示异常问题,代码头部插入一串代码
  1. import ctypes
  2. ctypes.windll.shcore.SetProcessDpiAwareness(1)
复制代码

TA的精华主题

TA的得分主题

 楼主| 发表于 2025-3-25 19:38 | 显示全部楼层

AI了一个小工具
电脑开机提示,显示IP,拍照并发送邮件。
要打包成文件,然后添加到开机自启动
代码中替换成自己的邮箱
  1. import requests
  2. from bs4 import BeautifulSoup
  3. import re
  4. import smtplib
  5. from email.mime.multipart import MIMEMultipart
  6. from email.mime.text import MIMEText
  7. from email.mime.base import MIMEBase
  8. from email import encoders
  9. from email.header import Header
  10. import os
  11. import cv2  # 导入opencv库


  12. def fetch_ip_info():
  13.     ip_url = 'https://2025.ip138.com/'
  14.     headers = {'User-Agent': 'Mozilla/5.0'}

  15.     try:
  16.         response = requests.get(ip_url, headers=headers, timeout=10)
  17.         response.encoding = response.apparent_encoding
  18.         ip_address = re.search(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}', response.text)
  19.         if not ip_address:
  20.             print("未能获取到本机公网IP地址")
  21.             return None

  22.         ip = ip_address.group()
  23.         print(f"当前IP地址:{ip}")

  24.         info_url = f"https://www.ipshudi.com/{ip}.htm"
  25.         response = requests.get(info_url, headers=headers, timeout=10)
  26.         response.encoding = 'utf-8'
  27.         soup = BeautifulSoup(response.text, 'html.parser')
  28.         table = soup.find('table')

  29.         if not table:
  30.             print("未找到数据表格")
  31.             return None

  32.         result = {}
  33.         for tr in table.find_all('tr'):
  34.             tds = tr.find_all('td')
  35.             if len(tds) != 2: continue
  36.             key, value = tds[0].get_text(strip=True), tds[1].get_text(" ", strip=True)

  37.             if key == "归属地":
  38.                 locations = [x for x in value.split("上报纠错")[0].strip().split() if x]
  39.                 location_mapping = {
  40.                     '省份': locations[1] if len(locations) > 1 else 'N/A',
  41.                     '城市': locations[2] if len(locations) > 2 else 'N/A',
  42.                     '区县': locations[3] if len(locations) > 3 else 'N/A',
  43.                 }
  44.                 result[key] = f"{location_mapping['省份']}, {location_mapping['城市']},{location_mapping['区县']}"
  45.             else:
  46.                 result[key] = value

  47.         return ip, result
  48.     except requests.exceptions.RequestException as e:
  49.         print(f"获取IP信息失败:{str(e)}")
  50.         return None


  51. def capture_image(file_path='captured_photo.jpg'):
  52.     cap = cv2.VideoCapture(0)

  53.     if not cap.isOpened():
  54.         print("无法打开摄像头")
  55.         return False

  56.     ret, frame = cap.read()
  57.     if ret:
  58.         cv2.imwrite(file_path, frame)
  59.         print(f"图像已保存到 {file_path}")
  60.         cap.release()
  61.         return True
  62.     else:
  63.         print("未能捕获到图像")
  64.         cap.release()
  65.         return False


  66. def send_email_with_attachments(ip_info, photo_path):
  67.     sender = '填写163发件邮箱'  # 发件人邮箱
  68.     password = '填写发件163邮箱授权码'  # 发件人邮箱授权码
  69.     receiver = '填写收件任意邮箱'  # 收件人邮箱
  70.     subject = '电脑已开机'

  71.     if ip_info:
  72.         ip, info = ip_info
  73.         body = (f"IP地址:{ip}\n"
  74.                 f"归属地:{info['归属地']}\n"
  75.                 f"运营商:{info.get('运营商', 'N/A')}\n"
  76.                 f"IP类型:{info.get('iP类型', 'N/A')}")
  77.     else:
  78.         body = "未能成功获取IP信息。\n"

  79.     msg = MIMEMultipart()
  80.     msg['From'] = Header(sender)
  81.     msg['To'] = Header(receiver)
  82.     msg['Subject'] = Header(subject, 'utf-8')
  83.     msg.attach(MIMEText(body, 'plain', 'utf-8'))

  84.     if os.path.exists(photo_path):
  85.         with open(photo_path, 'rb') as f:
  86.             mime = MIMEBase('image', 'jpg', filename=os.path.basename(photo_path))
  87.             mime.add_header('Content-Disposition', 'attachment', filename=os.path.basename(photo_path))
  88.             mime.add_header('X-Attachment-Id', '0')
  89.             mime.add_header('Content-ID', '<0>')
  90.             mime.set_payload(f.read())
  91.             encoders.encode_base64(mime)
  92.             msg.attach(mime)
  93.             print(f"照片 {photo_path} 已附加到邮件中")
  94.     else:
  95.         print(f"警告:文件 {photo_path} 不存在,跳过该附件。")
  96.         body += "\n注意:由于某种原因,未能成功拍摄并附加照片。"
  97.         msg.attach(MIMEText(body, 'plain', 'utf-8'))

  98.     try:
  99.         smtpObj = smtplib.SMTP_SSL('smtp.163.com', 465)
  100.         print("成功连接到 SMTP 服务器")

  101.         smtpObj.login(sender, password)
  102.         print("成功登录到 SMTP 服务器")

  103.         smtpObj.sendmail(sender, [receiver], msg.as_string())
  104.         print("邮件发送成功")

  105.         # 如果有照片且邮件发送成功后才删除照片
  106.         if os.path.exists(photo_path):
  107.             os.remove(photo_path)
  108.             print(f"本地文件 {photo_path} 已删除")
  109.     except smtplib.SMTPException as e:
  110.         print(f"无法发送邮件,错误信息:{str(e)}")


  111. if __name__ == "__main__":
  112.     ip_info = fetch_ip_info()

  113.     # 手动指定其他路径
  114.     photo_path = r"D:\ZQ.jpg"  # 示例:保存到 D 盘根目录

  115.     # 确保目录存在(如果需要)
  116.     #os.makedirs(os.path.dirname(photo_path), exist_ok=True)

  117.     if ip_info:
  118.         photo_taken = capture_image(photo_path)
  119.         send_email_with_attachments(ip_info, photo_path)
复制代码
您需要登录后才可以回帖 登录 | 免费注册

本版积分规则

1234

手机版|关于我们|联系我们|ExcelHome

GMT+8, 2025-3-27 23:05 , Processed in 0.019889 second(s), 9 queries , Gzip On, MemCache On.

Powered by Discuz! X3.4

© 1999-2023 Wooffice Inc.

沪公网安备 31011702000001号 沪ICP备11019229号-2

本论坛言论纯属发表者个人意见,任何违反国家相关法律的言论,本站将协助国家相关部门追究发言者责任!     本站特聘法律顾问:李志群律师

快速回复 返回顶部 返回列表