# 执行前先在服务器上安装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
通过python导出金蝶K3附件表t_Accessory中的附件到本地
最新推荐文章于 2025-04-11 20:43:45 发布