[UG 二次开发 python] 导出BOM表(包含图片)

只导出最底层的零件,零件的属性已经设置好,零件的截图生成后,放在零件的同一个文件夹下

用到了 xlsxwriter


# nx: threaded
# 导出BOM表
__version__ = "0.0.1"
__author__ = "unmht"
__blog__ = "https://www.cnblogs.com/unm001/"
from dataclasses import dataclass
from typing import Dict, List


import os
import NXOpen
import NXOpen.BlockStyler
import NXOpen.UF
import xlsxwriter
import NXOpen.Assemblies
from support import msgError

os.chdir(os.path.dirname(os.path.abspath(__file__)))


def getImgPath(p: NXOpen.Part):
    path = os.path.dirname(p.FullPath)
    name = p.Name
    return os.path.join(path, f"{name}.jpg")


@dataclass
class itm:
    p文件名称: str
    p图号: str = ""
    p名称: str = ""
    p数量: int = 0
    p材料: str = ""
    p规格: str = ""
    p备注: str = ""
    p图片: str = ""

    @classmethod
    def _props(cls):
        return ["文件名称"] + [i[1:] for i in cls.__dict__ if not i.startswith("_")]


def findallchild(
    ss: NXOpen.Session,
    ps: NXOpen.PartCollection,
    rtcom: NXOpen.Assemblies.Component,
    names: List[str],
    items: Dict[str, itm],
):
    coms = rtcom.GetChildren()
    if len(coms) > 0:
        for i in coms:
            chcoms = i.GetChildren()
            if len(chcoms) > 0:
                findallchild(ss, ps, i, names, items)
            else:
                iname = i.Name
                ipart = ps.FindObject(iname)
                if iname not in names:
                    names.append(iname)
                    items[iname] = itm(iname)
                items[iname].p数量 += 1
                pic = getImgPath(ipart)
                items[iname].p图片 = pic
                try:
                    items[iname].p图号 = ipart.GetUserAttribute(
                        "图号", NXOpen.NXObjectAttributeType.String, -3
                    ).StringValue
                except:
                    pass
                try:
                    items[iname].p名称 = ipart.GetUserAttribute(
                        "名称", NXOpen.NXObjectAttributeType.String, -3
                    ).StringValue
                except:
                    pass
                try:
                    items[iname].p材料 = ipart.GetUserAttribute(
                        "材料", NXOpen.NXObjectAttributeType.String, -3
                    ).StringValue
                except:
                    pass
                try:
                    items[iname].p规格 = ipart.GetUserAttribute(
                        "规格", NXOpen.NXObjectAttributeType.String, -3
                    ).StringValue
                except:
                    pass
                try:
                    items[iname].p备注 = ipart.GetUserAttribute(
                        "备注", NXOpen.NXObjectAttributeType.String, -3
                    ).StringValue
                except:
                    pass


def main(fpath):
    try:
        theSession = NXOpen.Session.GetSession()
        work = theSession.Parts.Work
        ps = theSession.Parts
        com = work.ComponentAssembly.RootComponent
        if com is not None:
            names = []
            items: Dict[str, itm] = {}
            findallchild(theSession, ps, com, names, items)
            # fpath = "d://bom.xlsx"
            if os.path.exists(fpath):
                os.remove(fpath)
            f = xlsxwriter.Workbook(fpath)
            ws1 = f.add_worksheet("bom")
            tts = itm._props()
            parm = {"x_scale": 0.05, "y_scale": 0.05}
            for i in range(len(tts)):
                ws1.write(0, i, tts[i])
            for i in range(len(names)):
                iname = names[i]
                iitm = items[iname]
                ws1.write(i + 1, 0, iitm.p文件名称)
                ws1.write(i + 1, 1, iitm.p图号)
                ws1.write(i + 1, 2, iitm.p名称)
                ws1.write(i + 1, 3, iitm.p数量)
                ws1.write(i + 1, 4, iitm.p材料)
                ws1.write(i + 1, 5, iitm.p规格)
                ws1.write(i + 1, 6, iitm.p备注)
                if iitm.p图片 != "" and os.path.exists(iitm.p图片):
                    ws1.insert_image(i + 1, 7, iitm.p图片, parm)
            f.close()
            # info(f.filename)
    except Exception as e:
        msgError(e)


if __name__ == "__main__":
    xlsxPath = os.path.join(os.getcwd(), "bom.xlsx")

    main(xlsxPath)

    if os.path.exists(xlsxPath):
        os.system(xlsxPath)



posted @ 2022-05-26 15:06  方头狮  阅读(1640)  评论(0)    收藏  举报