注:from conMySql import ConDb 这个是我自己封装的操作mysql工具,你们可以换成其它的操作数据库工具
为了方便理解,我把数据库的列改成中文的了,如果实际项目中,千万不要这样做
使用的设计模式:生产者消费者模式,(生产者:getgitem 消费者:toExecl)
知识点:进程池,进程队列,xlwt
import xlwt from conMySql import ConDb from multiprocessing import Pool,Manager import os,time def getgitem(q): con=ConDb() gcode=con.runSql('''select g_code from g_item group by g_code''') for i in gcode: gcode=i[0] q.put(gcode) #print(q.qsize()) def toExecl(q): # 写入execel,q参数是一个队列得到任务 print(q.empty()) while not q.empty(): con = ConDb() gcode=q.get() sql=''' SELECT 项目分类, 分类代码, 项目大类名称, 项目大类代码, CONCAT( LEFT(项目大类使用比例 * 100,6), '%' ) AS 项目大类比例, 项目名称, 项目代码, CONCAT(LEFT(使用比例 * 100,6), '%') AS 使用比例 FROM g_item WHERE g_code='{}' ORDER BY 项目分类 DESC, -- 项目大类使用比例 desc, 使用比例 DESC '''.format(gcode) ex=con.runSql(sql) workbook = xlwt.Workbook(encoding='utf-8') worksheet = workbook.add_sheet('明细表') for i in range(len(ex)): a, s, d, f, g, h, j, k=ex[i] print(a,s,d,f,g,h,j,k) worksheet.write(i, 0, str(a)) worksheet.write(i, 1, str(s)) worksheet.write(i, 2, str(d)) worksheet.write(i, 3, str(f)) worksheet.write(i, 4, str(g)) worksheet.write(i, 5, str(h)) worksheet.write(i, 6, str(j)) worksheet.write(i, 7, str(k)) workbook.save('{}.xls'.format(gcode)) if __name__ == '__main__': q = Manager().Queue() pool=Pool(4) pool.apply_async(getgitem, args=(q,)) time.sleep(2) for i in range(4): pool.apply_async(toExecl,args=(q,i)) pool.close() pool.join()