Python-批量导出excel加盟商出入库明细

需求:财务部门每月都会导出上个月每个加盟商的往来出入库明细,加盟商在DRP系统里大概有200+,通过人工的方法,一个一个查询导出的话,效率低、耗时长。最后工具搞定后只需要三分钟就搞定了所有的报表导出,实用性很高。

解决方案:考虑到这问题后我就在思考思路,确定好流程,之前看过北京理工大学的教授嵩天老师的Python课程,讲到程序的设计技巧就是IPO,输入、处理、输出三部分。顺着IPO思路就很清晰了。

输入:加盟商编码、上个月月初第一天、上个月月末最后一天

处理:从数据库中查询出结果以列表的形式保存,遍历列表写入excel文件

输出:保存到指定文件夹的excel表

先看下效果图:

打包后exe可执行程序

双击后开始运行下载:

Python-批量导出excel加盟商出入库明细_第1张图片
运行窗口

文件保存目录:

Python-批量导出excel加盟商出入库明细_第2张图片
文件导出后存放目录结构

excel内容示例:

Python-批量导出excel加盟商出入库明细_第3张图片
导出文件内容示例

开发环境:

Win7_64+Pycharm+Python3.5+SQLServer2008

打包工具:

Pyinstaller第三方工具

pyinstaller -F autoexport.py

涉及到:
数据库的存储过程调用、excel写入第三方库xlwt、元组列表转换、None处理、日期函数转字符串、for循环遍历、文件创建、字符串拼接等等

PS:基础知识真的很重要。

详细见代码注释:(代码没review写的糙,没有进一步优化)

拓展:后期可以拓展成可视化界面

代码如下:

  # -*- coding:utf-8 -*-

  # __author__ = 'codingme'

import pymssql

import os

import xlwt

from datetimeimport datetime

import time

import calendar

# 获取数据库连接

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()

# 获取加盟商时间段内出入库明细

def get_merchant_detail(conn, merchant_id, beg_date, end_date):

# SQLSERVER写好的查询存储过程

    select_merchant_flow_sql ='XXXXXXXXXXX'

    cursor = conn.cursor()

# 调用存储过程

    cursor.callproc(select_merchant_flow_sql, (merchant_id, beg_date, end_date))

# 结果集转换成list

    return list(cursor)

# EXCEL导出标题样式

def title_style():

style = xlwt.XFStyle()# 初始化样式

    font = xlwt.Font()# 为样式创建字体

    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()# 为样式创建字体

    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):

# 新建目录:运行目录+当前日期拼接新目录

    dir_name = os.path.join(os.getcwd(), time.strftime("%Y-%m-%d", time.gmtime()) +'出入库明细单')

if not os.path.exists(dir_name):

os.makedirs(dir_name)

file = xlwt.Workbook()# 创建工作簿

    '''

创建第一个sheet:

sheet1

'''

    sheet1 = file.add_sheet(u'sheet1', cell_overwrite_ok=True)

# 创建sheet表头

    sheet1.write_merge(0, 3, 0, 9, 'XXXX(深圳)有限公司加盟商出入库明细单', 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, '统计日期', 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行标题

    row0 = [u'单据类型', u'单据编号', u'销售类型', u'退货率', u'发货地编号', u'发货地名称', u'收货组织', u'收货组织名称',\

u'收货地编号', u'收货地名称', u'发货日期', u'年份', u'季节', u'款式名称', u'款号', u'颜色', u'尺码', u'发货折扣',\

u'发货数量', u'发货金额', u'备注']

for xin range(0, len(row0)):

sheet1.write(6, x, row0[x], set_style('Times New Roman', 220, True))

# 设置行宽度

        if xin [1, 5, 9, 13, 20]:

sheet1.col(x).width =256 *25

        else:

sheet1.col(x).width =256 *12

    # 从第七行开始遍历excel写入

    i =7

    # for循环写入存储过程返回值:加盟商出入库明细列表

    for rowin cursor:

for yin range(0, len(row0)):

# None值转换成0处理,然后转换成字符串

            sheet1.write(i, y, str(none_to_zero(row[y])))

# 移动到下一行继续循环

        i +=1

    # 保存文件名拼接: 结算方代码_结算方名称_出入库明细_日期年月.xls

    file_name =str(merchant_id).strip() +'_' + merchant_name +'_' +'出入库明细单' + get_first_day()[0:7] +'.xls'

    # 保存excel,目录+文件名

    file.save(os.path.join(dir_name, file_name))

print(file_name +'已经导出完成')

# NoneType转换成0

def none_to_zero(none_type):

if none_typeis None:

return 0

    else:

return none_type

# 获取当前日期字符串格式

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')

# 程序运行入口

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('开始导出所有加盟商出入库明细==========================')

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 +'所有加盟商出入库明细已经下载完成 %s' % end)

镇楼:人生苦短,我用Python

你可能感兴趣的:(Python-批量导出excel加盟商出入库明细)