Python operation execl, knowledge point process pool, queue, xlwt

Note: from conMySql import ConDb This is the operation mysql tool I encapsulated myself, you can replace it with other operation database tools

       In order to facilitate understanding, I changed the columns of the database to Chinese. If it is in an actual project, do not do this.


Design pattern used: producer consumer pattern, (producer: getgitem consumer: toExecl)

Knowledge points: process pool, process queue, xlwt

import xlwt
from conMySql import ConDb
from multiprocessing import Pool,Manager
import os,time
def getgitem(q):
    with=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):     # Write to execel, the q parameter is a queue to get the task
 print (q.empty())
     while not q.empty():    
        with = WithDb()
        gcode=q.get()
        sql= '''
           SELECT 
             project classification,
             classification code,
             project category name,
             project category code,
             CONCAT(
               LEFT (project category usage ratio * 100,6),
               '%'
             ) AS project category ratio,
             project name,
             Item code,
             CONCAT(LEFT(use ratio * 100,6), '%') AS use ratio 
           FROM
             g_item 
           WHERE g_code='{}'  
           ORDER BY Item classification DESC,
             -- use ratio desc for item categories,
             use ratio 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()

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325800946&siteId=291194637