通过python导出金蝶K3附件表t_Accessory中的附件到本地

# 执行前先在服务器上安装32位的Python,测试通过的版本是3.13,正常3.9以上都OK。
# 64位Python会报“没有注册类”(因为KDZIP.ZIP组件需要在32位环境中才能正常工作。)
# SQL查询语句在SQL2019上构造的,版本低的自己改下兼容查询语句
# 再终端运行 pip install pyodbc 和 pip install pywin32
# 然后复制下面代码存为“K3文件导出.py”的文件。
# 最后打开cmd命令行窗口
# C:\Users\htl258>py C:\Users\htl258\Desktop\K3文件导出.py
# 文件 20110408104139670_附件1.xls 已成功保存到 E:\Files_test
# 文件 20110408115637000_附件2.xls 已成功保存到 E:\Files_test
# 文件 20110408162705253_附件3.xls 已成功保存到 E:\Files_test


import pyodbc
import os
import win32com.client

# 数据库连接信息
server = '192.x.x.x'
database = 'AISxxxxxxxxxxxxxxxxxx'
username = 'sa'
password = 'xxxxxxxxxxxx'

# 创建连接字符串
conn_str = f'DRIVER={{SQL Server}};SERVER={server};DATABASE={database};UID={username};PWD={password}'
# print(conn_str)
try:
    # 连接到数据库
    conn = pyodbc.connect(conn_str)
    cursor = conn.cursor()

    # 查询表内容
    query = f"select CONCAT(FORMAT(FUploadTime, 'yyyyMMddHHmmssfff'),'_',FFileName) AS NewFileName,FData from t_Accessory where FSaveMode=0"
    cursor.execute(query)

    # 获取查询结果
    rows = cursor.fetchall()

    # 本地保存文件夹
    save_folder = r'E:\Files_test'
    if not os.path.exists(save_folder):
        os.makedirs(save_folder)

    # 处理每一行数据
    for row in rows:
        file_name = row[0]
        img = row[1]

        # 临时文件路径
        tmp_path = os.environ.get("tmp")
        if tmp_path is None:
            print("无法获取系统临时文件夹路径,跳过处理。")
            continue
        path1 = os.path.join(tmp_path, 'file1')
        path2 = os.path.join(tmp_path, 'file2')

        with open(path1, 'wb') as file:  # 创建临时文件
            file.write(img)  # 写入数据

        try:
            KDZIP = win32com.client.Dispatch('KDZIP.ZIP')  # 调用32位 COM 控件
            KDZIP.DeCompress(path1, path2)  # 解压被金蝶压缩的数据
        except Exception as e:
            print(f"解压文件 {file_name} 时出错: {e}")
            continue

        # 保存解压后的文件到指定文件夹
        save_path = os.path.join(save_folder, file_name)
        try:
            with open(path2, 'rb') as src_file, open(save_path, 'wb') as dst_file:
                dst_file.write(src_file.read())
            print(f"文件 {file_name} 已成功保存到 {save_folder}")
        except Exception as e:
            print(f"保存文件 {file_name} 时出错: {e}")

    # 关闭连接
    cursor.close()
    conn.close()

except pyodbc.Error as e:
    print(f"数据库连接或查询出错: {e}")
except Exception as e:
    print(f"发生未知错误: {e}")

# htl258_Tony 20250323

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值