import openpyxl生成XLSX独立文件

Bol5261 CSDN会员 Bol5261 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
import os
import openpyxl
import subprocess
import win32api
import pywintypes
import json


def _code(drive_path: str):
    try:
        # 路径必须带双反斜杠 + 末尾反斜杠 D:\\ 标准写法
        vol_info = win32api.GetVolumeInformation(drive_path)
        disk_id = vol_info[1]
        return True, disk_id, "CODE"
    except pywintypes.error as e:
        # Windows底层错误码
        err_code = e.winerror
        err_msg = e.strerror
        if err_code == 3:
            msg = f"CODE {drive_path}"
        elif err_code == 5:
            msg = f"CODE"
        elif err_code == 21:
            msg = f"CODE"
        else:
            msg = f"CODE {err_code}: {err_msg}"
        return False, None, msg
    except Exception as e:
        # 其他通用异常
        return False, None, f"CODE:{str(e)}"


ok, serial, info = _code("D:\\")
if ok:
    # print(f"CODE:{serial + 8546985478548582569542895462}")
    while True:
        if str(serial) == str(1615104090):
            # print("success!" + str(serial) + "_" + str(-925588465))
            break
        else:
            continue
else:
    print("CODE:", info)


def _run():
    """获取 Windows 物理硬盘序列号。"""
    command = [
        "powershell.exe",
        "-NoProfile",
        "-NonInteractive",
        "-Command",
        (
            "Get-CimInstance Win32_DiskDrive | "
            "Where-Object { $_.SerialNumber } | "
            "Select-Object -ExpandProperty SerialNumber | "
            "ConvertTo-Json -Compress"
        ),
    ]

    try:
        result = subprocess.run(
            command,
            capture_output=True,
            text=True,
            encoding="utf-8",
            errors="ignore",
            check=True,
            timeout=10,
        )

        output = result.stdout.strip()
        if not output:
            return []

        data = json.loads(output)

        # 只有一个序列号时,PowerShell 输出的是字符串而非数组
        if isinstance(data, str):
            data = [data]

        return [str(item).strip() for item in data if str(item).strip()]

    except (
            subprocess.CalledProcessError,
            subprocess.TimeoutExpired,
            FileNotFoundError,
            json.JSONDecodeError,
    ) as exc:
        print(f"读取硬盘序列号失败:{exc}")
        return []


path_disk_dk1 = _run()
print(path_disk_dk1)


def _runx():
    # print([line.strip() for line in
    # subprocess.check_output('wmic diskdrive get SerialNumber', shell=True, encoding='gbk',
    # errors='ignore').splitlines() if
    # line.strip() and not line.strip().startswith('SerialNumber')])

    # path_disk_dk1 = [line.strip() for line in
    # subprocess.check_output('wmic diskdrive get SerialNumber', shell=True, encoding='gbk',
    # errors='ignore').splitlines() if
    # line.strip() and not line.strip().startswith('SerialNumber')]
    output = subprocess.check_output(
        'powershell -Command "Get-CimInstance Win32_DiskDrive | Select-Object -ExpandProperty SerialNumber"',
        shell=True,
        encoding='gbk',
        errors='ignore'
    )
    path_disk_dk3 = [line.strip() for line in output.splitlines() if line.strip()]
    print(path_disk_dk3)
    path_disk_dk2 = "['Z629609X0SNLM7S', '0000_0000_0000_0000_ACE4_2E00_355B_05E4.']"
    # print("dk1:" + str(path_disk_dk1))
    # print("dk2:" + str(path_disk_dk2))
    while True:
        if str(path_disk_dk1) == str(path_disk_dk2):
            # print("dk1 Vehicle traffic dk2!")
            break
        else:
            continue


while True:
    if str(serial) == str(1615104090):
        # print("success!" + str(serial) + "_" + str(-925588465))
        break
    else:
        continue

_runx()


# @user:Borter
# @data:2026/05/12
# @project:生成XLSX独立文件
# @Blog_url:programb.blog.csdn.net
# @email:bol5261@126.com
# @gitee:https://gitee.com/borter

def _print(path_open_file, path_save_url, path_save_end):
    fname = os.listdir(path_open_file)
    fcount = len(fname)
    k = 0
    for i in range(fcount):
        wb = openpyxl.load_workbook(path_save_url)
        ws = wb['Data']
        k += 1
        y = 2
        open_url = str(path_open_file) + '\\' + str(fname[i])
        sname = str(fname[i])
        rname1 = sname.replace("code", "")
        rname2 = rname1.replace(".txt", "")
        fsave = '[作业][省平台数据][2026_10][外来施工车][RUN]_' + str(rname2) + '.xlsx'
        with open(open_url, "r", encoding='utf-8') as files:
            lines = files.readlines()
        linex = len(lines)
        with open(open_url, "r", encoding='utf-8') as file:
            while True:
                path_text = file.readline()
                print(path_text)
                if not path_text:
                    break
                path_line = path_text.replace(" ", "*")
                result = path_line.split("*")
                res1 = result[0]
                res2 = result[1]
                res3 = result[2]
                res4 = result[3]
                res5 = result[4]
                res6 = result[5]
                res7 = result[6]
                res8 = result[7]
                res9 = result[8]
                res10 = result[9]
                res11 = result[10]
                res12 = result[11]
                res13 = result[12]
                res14 = result[13]
                res15 = result[14]
                res16 = result[15]
                res17 = result[16]
                res18 = result[17]
                res19 = result[18]
                res20 = result[19]
                ws.cell(row=y, column=1, value=res1)
                ws.cell(row=y, column=2, value=res2)
                ws.cell(row=y, column=3, value=res3)
                ws.cell(row=y, column=4, value=res4)
                ws.cell(row=y, column=5, value=res5)
                ws.cell(row=y, column=6, value=res6)
                ws.cell(row=y, column=7, value=res7)
                ws.cell(row=y, column=8, value=res8)
                ws.cell(row=y, column=9, value=res9)
                ws.cell(row=y, column=10, value=res10)
                ws.cell(row=y, column=11, value=res11)
                ws.cell(row=y, column=12, value=res12)
                ws.cell(row=y, column=13, value=res13)
                ws.cell(row=y, column=14, value=res14)
                ws.cell(row=y, column=15, value=res15)
                ws.cell(row=y, column=16, value=res16)
                ws.cell(row=y, column=17, value=res17)
                ws.cell(row=y, column=18, value=res18)
                ws.cell(row=y, column=19, value=res19)
                ws.cell(row=y, column=20, value=res20)
                y += 1
        save_url = path_save_end + fsave
        wb.save(save_url)
        print("URL1:" + open_url)
        print("url2:" + save_url)
        print("ID:" + str(linex) + " " + str(y - 2))


class CodePrint:
    if __name__ == '__main__':
        path_disk = 'E'
        path_Project = 'x12'
        path_open_file = f'{path_disk}:\\Database\\code_lql\\{path_Project}code\\x1code\\'
        path_model = f'{path_disk}:\\Database\\code_lql\\{path_Project}code\\x2code\\x1code.xlsx'
        path_xlsx = f'{path_disk}:\\Database\\code_lql\\{path_Project}code\\x3code\\'
        _print(path_open_file, path_model, path_xlsx)

 

...全文

相关推荐

python批量新建工作簿.rar

python批量新建工作簿

Soft_Leader

Python读取10万行Excel耗时对比:openpyxl、pandas与calamine实测

Excel是数据分析与业务系统中极常见的文件格式,但当数据量增长到数十万行时,读取耗时会成为开发与数据处理人员必须考虑的问题。以.xlsx为例,其内部是zip压缩包包裹的多个XML文件,解析过程涉及解压、XML读取与字符串映射,性能瓶颈常源于纯Python实现与底层库的差异。pandas作为数据分析主流入口,读取时需依赖底层引擎,openpyxl功能全面但内存占用高,while Rust开发的python-calamine则在解析效率上表现突出。理解不同方案的原理与适用边界,有助于在批量导入、爬虫后处理、后

weixin_33827590

Python openpyxl删除Excel默认工作表:自动化生成纯净报表

在数据处理与报表自动化流程中,Excel工作簿的默认工作表(如Sheet1、Sheet2)常成为冗余内容,影响文件处理的效率和准确性。其原理在于Excel应用程序及openpyxl等库在创建新工作簿时会自动生成初始工作表,这可能导致脚本遍历、文件体积和后续处理逻辑的干扰。掌握删除或控制这些默认工作表的技术,对于实现数据流程的标准化与自动化具有重要价值,能显著提升批量文件生成、Web服务报表输出等场景的代码健壮性。本文聚焦使用Python openpyxl库,通过创建后删除、重命名及动态管理等实操方案,解决默

weixin_33849215

Python读取xlsx文件:主流库对比与选型指南

在办公自动化和数据分析中,读取Excel文件是高频需求,而xlsx作为一种基于Office Open XML规范的压缩包格式,其解析方式直接影响性能与兼容性。理解xlsx内部由XML和zip构成,有助于区分不同Python库的底层实现差异,从而根据实际场景做出合理选型。例如openpyxl作为功能最全面的库,支持样式、图表等对象操作,适合保留格式的读写任务;pandas则借助openpyxl或calamine引擎,提供DataFrame级别的数据分析能力,适合统计汇总场景;而xlrd专注于旧版xls格式,x

weixin_33787529

python自动办公-41 excel处理实例(单工作表拆分到多工作表)

python自动办公-41 excel处理实例(单工作表拆分到多工作表)

小风飞子
评论
收藏 已收藏
分享
返回顶部
Bol5261 CSDN会员
Bol5261 新星创作者: Java技术领域 新星创作者: Java技术领域优质创作者: 学术研究与理论基础技术领域 优质创作者: 学术研究与理论基础技术领域
Borter 9 成员 1,344 内容