Python读取Access数据库并输出表格数据为xls

简单写了个脚本,结论是运行手感有点慢。。
使用时需要本机电脑安装有access数据库引擎,我这边只有64位的,不过脚本本身应该无关64或32位。

# -*- coding: UTF-8 -*-
from distutils.command.config import config
import encodings
from operator import indexOf
import sys,os
if hasattr(sys, 'frozen'):
	os.environ['PATH'] = sys._MEIPASS + ";" + os.environ['PATH']
import xlrd,xlwt,math,json
import pypyodbc


def readMdb(conf_path):
	with open(conf_path)as fr:
		configuration = fr.read()
	configs=json.loads(configuration)
	mdb_path=configs["mdb"] 
	tb=configs["table"] 
	columns=configs["cols"]
	wheres=configs["where"] 
	outFile=config["outFile"]
	cols=columns.split(",")
	# 读取配置指定位置的数据库
	conn = pypyodbc.connect(r"Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" + mdb_path + ";Uid=;Pwd=;")
	
	# 读取配置指定表及字段,并写成xls
	cursor = conn.cursor()
	if wheres=='':
		sql="select %s from %s"%(columns,tb)
	else:
		sql="select %s from %s where %s"%(columns,tb,wheres)
	print(sql)
	res=cursor.execute(sql)

	new_workbook = xlwt.Workbook()
	new_sheet = new_workbook.add_sheet(tb)
	for i in range(0,len(cols)):
		new_sheet.write(0,i,cols[i])
	index = 1
	for i in list(res):
		for x in range(0,len(cols)):
			new_sheet.write(index,x,i[x])
		index+=1
	new_workbook.save(outFile,tb)

if __name__=='__main__':
	# 配置文件
	conf_path = sys.argv[1]
	readMdb(conf_path)

使用的 conf_path 文件格式如下:

{
   
    "mdb":"D:/Data.mdb",
    "where":"(((tb1.[col1])='sample1') and ((tb1.[col2])='2022-01-20'))",
    "cols":"col1,col2,col3,col4,col5",
    "table":"tb1",
    "outFile":"D:/out.xlsx"
}
全部评论

相关推荐

05-12 13:14
已编辑
中山大学 算法工程师
点赞 评论 收藏
分享
谁知道呢_:要掉小珍珠了,库库学三年,这个结果
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务