需求:財務(wù)部門每月都會導(dǎo)出上個月每個加盟商的往來出入庫明細(xì),加盟商在DRP系統(tǒng)里大概有200+,通過人工的方法,一個一個查詢導(dǎo)出的話,效率低、耗時長。最后工具搞定后只需要三分鐘就搞定了所有的報表導(dǎo)出,實(shí)用性很高。
解決方案:考慮到這問題后我就在思考思路,確定好流程,之前看過北京理工大學(xué)的教授嵩天老師的Python課程,講到程序的設(shè)計(jì)技巧就是IPO,輸入、處理、輸出三部分。順著IPO思路就很清晰了。
輸入:加盟商編碼、上個月月初第一天、上個月月末最后一天
處理:從數(shù)據(jù)庫中查詢出結(jié)果以列表的形式保存,遍歷列表寫入excel文件
輸出:保存到指定文件夾的excel表
先看下效果圖:

打包后exe可執(zhí)行程序
雙擊后開始運(yùn)行下載:
運(yùn)行窗口
文件保存目錄:
文件導(dǎo)出后存放目錄結(jié)構(gòu)
excel內(nèi)容示例:
導(dǎo)出文件內(nèi)容示例
開發(fā)環(huán)境:
Win7_64+Pycharm+Python3.5+SQLServer2008
打包工具:
Pyinstaller第三方工具
pyinstaller -F autoexport.py
涉及到:
數(shù)據(jù)庫的存儲過程調(diào)用、excel寫入第三方庫xlwt、元組列表轉(zhuǎn)換、None處理、日期函數(shù)轉(zhuǎn)字符串、for循環(huán)遍歷、文件創(chuàng)建、字符串拼接等等
PS:基礎(chǔ)知識真的很重要。
詳細(xì)見代碼注釋:(代碼沒review寫的糙,沒有進(jìn)一步優(yōu)化)
拓展:后期可以拓展成可視化界面
代碼如下:
# -*- coding:utf-8 -*-
# __author__ = 'codingme'
import pymssql
import os
import xlwt
from datetimeimport datetime
import time
import calendar
# 獲取數(shù)據(jù)庫連接
def get_conn():
server ='ip:port'
datebase ='database_name'
user ='user'
password ='password'
conn= pymssql.connect(server, user, password, datebase)
return conn
# 獲取加盟商代碼和名稱
def get_merchant_list(conn):
# M5030'[M|L|K]5%'
select_merchant_sql ="select merchantid, shutname from j_merchant where merchantid like '[M|L|K]5%' "
cursor = conn.cursor()
cursor.execute(select_merchant_sql)
return cursor.fetchall()
# 獲取加盟商時間段內(nèi)出入庫明細(xì)
def get_merchant_detail(conn, merchant_id, beg_date, end_date):
# SQLSERVER寫好的查詢存儲過程
select_merchant_flow_sql ='XXXXXXXXXXX'
cursor = conn.cursor()
# 調(diào)用存儲過程
cursor.callproc(select_merchant_flow_sql, (merchant_id, beg_date, end_date))
# 結(jié)果集轉(zhuǎn)換成list
return list(cursor)
# EXCEL導(dǎo)出標(biāo)題樣式
def title_style():
style = xlwt.XFStyle()# 初始化樣式
font = xlwt.Font()# 為樣式創(chuàng)建字體
font.name ='Times New Roman'
font.bold =True
font.color_index =4
font.height =500
style.font = font
# style.borders = borders
al = xlwt.Alignment()
al.horz = xlwt.Alignment.HORZ_CENTER
al.vert = xlwt.Alignment.VERT_CENTER
style.alignment = al
return style
# excel表格單元格格式
def set_style(name, height, bold=False):
style = xlwt.XFStyle()# 初始化樣式
font = xlwt.Font()# 為樣式創(chuàng)建字體
font.name = name# 'Times New Roman'
font.bold = bold
font.color_index =4
font.height = height
# borders= xlwt.Borders()
# borders.left= 6
# borders.right= 6
# borders.top= 6
# borders.bottom= 6
style.font = font
# style.borders = borders
al = xlwt.Alignment()
al.horz = xlwt.Alignment.HORZ_LEFT
style.alignment = al
return style
# 加盟商對賬單寫入excel表格
def write_excel_merchant(merchant_id, merchant_name, cursor):
# 新建目錄:運(yùn)行目錄+當(dāng)前日期拼接新目錄
dir_name = os.path.join(os.getcwd(), time.strftime("%Y-%m-%d", time.gmtime()) +'出入庫明細(xì)單')
if not os.path.exists(dir_name):
os.makedirs(dir_name)
file = xlwt.Workbook()# 創(chuàng)建工作簿
'''
創(chuàng)建第一個sheet:
sheet1
'''
sheet1 = file.add_sheet(u'sheet1', cell_overwrite_ok=True)
# 創(chuàng)建sheet表頭
sheet1.write_merge(0, 3, 0, 9, 'XXXX(深圳)有限公司加盟商出入庫明細(xì)單', title_style())
sheet1.write(4, 0, '加盟商名稱', set_style('Times New Roman', 220, True))
sheet1.write(4, 1, merchant_name + merchant_id, set_style('Times New Roman', 220, True))
sheet1.write(5, 0, '統(tǒng)計(jì)日期', set_style('Times New Roman', 220, True))
sheet1.write(5, 1, get_first_day()+'至'+get_last_day(), set_style('Times New Roman', 220, True))
sheet1.write(5, 2, '打印日期', set_style('Times New Roman', 220, True))
sheet1.write(5, 3, time_format(time.gmtime()), set_style('Times New Roman', 220, True))
# 生成表頭第6行標(biāo)題
row0 = [u'單據(jù)類型', u'單據(jù)編號', u'銷售類型', u'退貨率', u'發(fā)貨地編號', u'發(fā)貨地名稱', u'收貨組織', u'收貨組織名稱',\
u'收貨地編號', u'收貨地名稱', u'發(fā)貨日期', u'年份', u'季節(jié)', u'款式名稱', u'款號', u'顏色', u'尺碼', u'發(fā)貨折扣',\
u'發(fā)貨數(shù)量', u'發(fā)貨金額', u'備注']
for xin range(0, len(row0)):
sheet1.write(6, x, row0[x], set_style('Times New Roman', 220, True))
# 設(shè)置行寬度
if xin [1, 5, 9, 13, 20]:
sheet1.col(x).width =256 *25
else:
sheet1.col(x).width =256 *12
# 從第七行開始遍歷excel寫入
i =7
# for循環(huán)寫入存儲過程返回值:加盟商出入庫明細(xì)列表
for rowin cursor:
for yin range(0, len(row0)):
# None值轉(zhuǎn)換成0處理,然后轉(zhuǎn)換成字符串
sheet1.write(i, y, str(none_to_zero(row[y])))
# 移動到下一行繼續(xù)循環(huán)
i +=1
# 保存文件名拼接: 結(jié)算方代碼_結(jié)算方名稱_出入庫明細(xì)_日期年月.xls
file_name =str(merchant_id).strip() +'_' + merchant_name +'_' +'出入庫明細(xì)單' + get_first_day()[0:7] +'.xls'
# 保存excel,目錄+文件名
file.save(os.path.join(dir_name, file_name))
print(file_name +'已經(jīng)導(dǎo)出完成')
# NoneType轉(zhuǎn)換成0
def none_to_zero(none_type):
if none_typeis None:
return 0
else:
return none_type
# 獲取當(dāng)前日期字符串格式
def time_format(in_time):
times = time.strftime("%Y-%m-%d", in_time)
return times
# 上個月最后一天
def get_last_day():
d = datetime.now()
c = calendar.Calendar()
year = d.year
month = d.month
if month ==1:
month =12
year -=1
else:
month -=1
days = calendar.monthrange(year, month)[1]
return datetime(year, month, days).strftime('%Y-%m-%d')
# 上個月第一天
def get_first_day():
d = datetime.now()
c = calendar.Calendar()
year = d.year
month = d.month
if month ==1:
month =12
year -=1
else:
month -=1
return datetime(year, month, 1).strftime('%Y-%m-%d')
# 程序運(yùn)行入口
if __name__ =='__main__':
conn = get_conn()
merchant_list = get_merchant_list(conn)
first_day = get_first_day()
last_day = get_last_day()
start = time.time()
print('開始導(dǎo)出所有加盟商出入庫明細(xì)==========================')
for merchantin merchant_list:
merchant_id = merchant[0]
merchant_name = merchant[1]
cursor = get_merchant_detail(conn, merchant_id, first_day, last_day)
if len(cursor) ==0:
continue
else:
write_excel_merchant(merchant_id, merchant_name, cursor)
end = time.time() - start
print(last_day +'所有加盟商出入庫明細(xì)已經(jīng)下載完成 %s' % end)