由Python生成采购清单BOM

2021-01-20 10:26:00 浏览数 (1)

参考链接: Python清单

采购清单BOM的生成 

问题: 

公司在原型板焊接的时候,经常需要采购多块板子的器件,而其中很多器件型号都是相同的。采购部门会要求我们把所有相同的型号归类。  

这是一件耗时而又无趣的工作, 所以需要最好能够自动生成采购清单。 

解决办法: 

因为我们的BOM文件都是excel格式, 而经常看到Python培训的广告, 展示其能够处理excel的强大功能。 

因此选择使用Python自己写一个程序来执行合并操作。 

解决步骤: 

1, 首先看看我们的BOM表的格式 

对于采购人员来说, Designator 和footprint是不需要关注的, 他们关注点主要在器件型号, 厂家以及购买数量和购买渠道。 

采购清单的格式主要如下 

2, Python, 你强你上 

附上具体的代码, 本人第一次写Python,肯定有不优雅的地方,欢迎高手们将程序改进。 

import pandas as pd

import os

import numpy as np

#how to use

#1, copy all board BOMs to same directory with this python file

#2, Run this script in python IDE or other python software

#3, input the QTY for each board

#4, it generate a Purchase.xlsx in current folder

output_file_name="Purchase.xlsx"

fileNames=[]

keyCode="StockCode"

Comment="Comment"

Desc="Description"

QTY="Quantity"

Manufature="Manufature"

Mpart="Manufacture  part"

Supplier="Supplier1"

SPart="Suppiler1 part"

#finalCols=[keyCode, Comment, Desc, Manufature, Mpart, Supplier, SPart, QTY]

def pre_process_excelfile(excel_files):

       global  fileNames

       path, fileName = os.path.split(excel_files)

       fileName, file_extension = os.path.splitext(fileName)

       #read excel file

       dataframe = pd.read_excel(excel_files);

       #search position of Stockcode in

       row_start=None

       for row in range(dataframe.shape[0]): 

              for col in range(dataframe.shape[1]):

                     if dataframe.iat[row,col] == keyCode:

                            row_start = row

                            keyCodeColumn=col

                            #print(row_start)

                            break;

       #set column names and delete file header part

       if(row_start is None):

              print("stockCode not found, not BOM filen")

       elif(row_start > 1):

                     dataframe.columns = dataframe.iloc[row_start]

                     dataframe.drop(dataframe.index[row_start], inplace=True)

                     dataframe.drop(dataframe.index[range(0,row_start)],axis=0, inplace=True)

       #delete file tails

       dataframe=dataframe.loc[dataframe[keyCode].notnull()]

       #delete columns

       dataframe = dataframe.dropna(axis = 1, how = 'all')

       #pick up columns and change  qty column name

       dataframe = dataframe[[keyCode, Comment, Desc, Manufature, Mpart, Supplier, SPart, QTY]]

       dataframe.columns = dataframe.columns.str.replace(QTY,fileName)

       fileNames.append(fileName)

       #input QTY boards for assembly

       BOMQty=input("How manmy boards needed for " fileName " ?")

       print(BOMQty)

       dataframe[fileName '.QTY']= BOMQty

       return dataframe

#

path=os.getcwd()

print(path)

#delete output file to avoid combining it

outputFile=os.path.join(path, output_file_name)

if os.path.isfile(outputFile):

       os.remove(outputFile)

result=pd.DataFrame()

for filename in os.listdir (path):

       if filename.endswith ('.xlsx'):

              read_filename=os.path.join(path, filename)

              dataframe=pre_process_excelfile(read_filename)

              if(result.empty):

                     result=dataframe;

              else:

                     result = result.merge(dataframe, on=[keyCode, Comment, Desc, Manufature, Mpart, Supplier, SPart], how='outer', sort=True)

#sort data according to StockCode

dataframe=result

dataframe=dataframe.sort_values(by=keyCode)

dataframe.groupby(keyCode)

#fill nan with 0 in order to do multipy operation

dataframe.replace(np.nan, 0, inplace=True)

#calculate total

dataframe['total']=0

for eachfile in fileNames:

      dataframe[eachfile] = dataframe[eachfile].astype(int)

      dataframe[eachfile '.QTY'] = dataframe[eachfile '.QTY'].astype(int)

      dataframe['total']=dataframe['total'] (dataframe[eachfile]) * (dataframe[eachfile '.QTY'])

#fill back with nan

dataframe.replace(0,np.nan, inplace=True)

#writeback a excel file

result_filename=os.path.join(path, output_file_name)

dataframe.to_excel(result_filename, index = False)

print("Done, and Generate " output_file_name " at " path " !")

 3, 代码的使用方法 

1, 拷贝代码并保存为merge excels.py 

2, 安装PythonIDLE 

本人使用的版本是3.8.2 

3, 拷贝各个PCB板的对应BOM文件到相同目录下, 和merge excels.py在同一目录。 

4,运行PythonIDLE 

File->open(merge excels.py) 

然后直接run 

根据提示输入制板的数量。 本人在这里展示了板子1需要购买的元器件的套数是10, 板子2的套数是20 

当前目录下会生成新的文件Purchase.xlsx。 

文件中的H列是单个板子1的数量, 列I是板子的套数。J列是单个板子2的数量, 列K是板子的套数 

最后的总数total=H*I J*K.

0 人点赞