Creating parts with parameters from an Excel table

Creating parts with parameters from an Excel table

romanazaur
Explorer Explorer
300 Views
4 Replies
Message 1 of 5

Creating parts with parameters from an Excel table

romanazaur
Explorer
Explorer

Hello. I have a flat piece of sheet metal with text embossed on it. The part is always the same, but the text on it needs to be different, for example “St-23” than “St-25” than “Rt-45”. I have an Excel table in which there are 2 columns - the name of the part and the number of parts. I would like to make a macro or iLogic rule that would take the text for this part from the first row of the first column of the table, then save the flat pattern in .dxf format with the name "text_quanty.dxf". for example St-23_2.dxf. And it continued until it reached an empty line.

 

Ideally, saving should not be via flat patern->save copy as, but using export face as, because when saving via flat patern the letter splines looks ugly. Can you help me with this please?

0 Likes
301 Views
4 Replies
Replies (4)
Message 2 of 5

james.collinsPWQR2
Advocate
Advocate

Hi romanazaur,

Try the following code, I haven't added much in the way of error checking and I couldn't get it to export faces that have bends, but it should be a good start.

 

 

Imports Excel
Imports Microsoft.Office.Interop.Excel        ' To use Excel
Imports System.Runtime.InteropServices        ' To use Marshal
Imports System.Activator                      ' To use CreateInstance
Sub Main()
    ' Initialize Inventor objects
    Dim invApp As Inventor.Application = ThisApplication
    Dim invDoc As PartDocument = invApp.ActiveDocument
    Dim compDef As SheetMetalComponentDefinition = invDoc.ComponentDefinition
    Dim flatPattern As FlatPattern = compDef.FlatPattern
    ' Path to the Excel file 
    Dim excelFilePath As String = "C:\Temp\DXFNameQTY.xlsx" '<<<<change this to match you excel file
    ' Open Excel
    Dim xlApp As Object = CreateObject("Excel.Application")

    If xlApp Is Nothing Then
        MessageBox.Show("Excel is not installed properly.")
        Exit Sub
    End If

    ' Open workbook
    Dim xlWorkbook As Object = xlApp.Workbooks.Open(excelFilePath)
    Dim xlWorksheet As Object = xlWorkbook.Worksheets(1)
    
    ' Determine DXF file path and emboss feature
    Dim fileNameWithPath As String = invDoc.FullDocumentName
    Dim fileNamePos As Long = InStrRev(fileNameWithPath, "\", -1)
    Dim embossFeat As EmbossFeature = compDef.Features.EmbossFeatures.Item(1)
    Dim aSideDef As ASideDefinition = compDef.FlatPattern.ASideFace
    ' Find the face with the most edges, as this should be the one with the emboss
    Dim faceWithMostEdges As Face = Nothing
    Dim faceEdgeCount As Double = 0
    For Each ASideFace As Face In aSideDef.Faces
        If ASideFace.Edges.Count > faceEdgeCount Then
            faceWithMostEdges = ASideFace
            faceEdgeCount = ASideFace.Edges.Count
        End If
    Next

    Dim tempSketch As PlanarSketch = Nothing

    ' Loop through each row in the Excel file
    Dim row As Integer = 1
    Do While xlWorksheet.Cells(row, 1).Value IsNot Nothing
        Dim partName As String = xlWorksheet.Cells(row, 1).Value.ToString()
        Dim quantity As String = xlWorksheet.Cells(row, 2).Value.ToString()
'Create a text user parameter in the part file that will be used for the emboss
PartName = partName
        Dim dxfFileName As String = partName & "_" & quantity & ".dxf"
        Dim dxfFilePath As String = Left(fileNameWithPath, fileNamePos) & dxfFileName
        Try
            flatPattern.Edit()
        Catch
            ' Handle possible error when editing the flat pattern
        End Try
        
        If row = 1 Then
            ' Add sketch to selected face
            tempSketch = compDef.Sketches.Add(faceWithMostEdges, True)
            tempSketch.Name = "TempDXF_Delete"
        End If

        invDoc.Update2(True)

        ' Write the sketch out as DXF
        tempSketch.DataIO.WriteDataToFile("DXF", dxfFilePath)
        
        ' Proceed to the next row
        row += 1
    Loop
    
    ' Delete the temporary sketch
    Try
        tempSketch.Delete()
    Catch
        ' Handle possible error when deleting the sketch
    End Try
    
    ' Close the workbook without saving
    xlWorkbook.Close(False)
    ' Quit Excel
    xlApp.Quit()

    ' Clean up
    ReleaseObject(xlWorksheet)
    ReleaseObject(xlWorkbook)
    ReleaseObject(xlApp)
End Sub

' Function to release objects
Private Sub ReleaseObject(ByVal obj As Object)
    Try
        Marshal.ReleaseComObject(obj)
        obj = Nothing
    Catch ex As Exception
        obj = Nothing
    Finally
        GC.Collect()
    End Try
End Sub

 

You will also need to create a Text User Parameter (PartName), that will be used for the emboss:

jamescollinsPWQR2_0-1738714803932.png

 

 Cheers,

 

James

Message 3 of 5

romanazaur
Explorer
Explorer

Thanks a lot for your help, this is very close to what I need. I previously did exactly this by embossing the PartNumber parameter. But it seems the code does not assign the PartNumber parameter from the table to the part, or assigns, but does not update the emboss operation before saving the dxf. Thus, all created dxf files have the same markings, the ones that were in the original part, and not in the table.
Can you please also tell me what needs to be entered here
Dim excelFilePath As String = "C:\Temp\DXFNameQTY.xlsx"  - if my .xlsl file is in the same directory as the part

0 Likes
Message 4 of 5

james.collinsPWQR2
Advocate
Advocate

Hi romanazaur,

 

I was able to get the emboss to update correct for each partnumber, but I'm struggling to get the data.io to clear/close after each export. Thats why the filename is correct but the contents are all the same.
For this line of code just replace the ?? with your excel file path and name:  Dim excelFilePath As String = "??.xlsx"

 

I will keep trying to resolve the issue with the dxf's looking the same.

 

Have a good one,

 

James

0 Likes
Message 5 of 5

james.collinsPWQR2
Advocate
Advocate

Hi romanazaur,

 

I wasn't able to get the rule to work completely from the part document, I had to create new temporary parts and place them into an assembly and from there run a second rule to create the dxfs. Hardly an ideal solution, but it works.

 

Here's the code to be run from your sheet metal part:

Imports Excel
Imports Microsoft.Office.Interop.Excel        ' To use Excel
Imports System.Runtime.InteropServices        ' To use Marshal
Imports System.Activator                      ' To use CreateInstance
Class ThisRule

Dim app As Inventor.Application

Sub Main()
	' Initialize Inventor objects
	app = ThisApplication
	Dim partDoc As PartDocument = app.ActiveDocument
	Dim shtComponentDefinition As SheetMetalComponentDefinition
	Dim sheetMetalSubType As String = "{9C464203-9BAE-11D3-8BAD-0060B0CE6BB4}"
	Dim docSubType As String = partDoc.SubType
	If docSubType = sheetMetalSubType Then 'sheet metal
		shtComponentDefinition = partDoc.ComponentDefinition
	Else
		MessageBox.Show("This rule should only be run from SheetMetal Parts." & vbLf & _
		"", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error)	
	End If
	Dim flatPatt As FlatPattern = shtComponentDefinition.FlatPattern
	Dim filesToOpen As String = "FilesToOpen"
	' Path to the Excel file 
	Dim excelFilePath As String = "C:\Temp\DXFNameQTY.xlsx" '<<<<change this to match you excel file
	' Open Excel
	Dim xlApp As Object = CreateObject("Excel.Application")
	If xlApp Is Nothing Then
		MessageBox.Show("Excel is not installed properly.")
		Exit Sub
	End If
	' Open workbook
	Dim xlWorkbook As Object = xlApp.Workbooks.Open(excelFilePath)
	Dim xlWorksheet As Object = xlWorkbook.Worksheets(1)
	' Determine DXF file path and emboss feature
	Dim fileNameWithPath As String = partDoc.FullDocumentName
	Dim fileNamePos As Long = InStrRev(fileNameWithPath, "\", -1)
	Dim embossFeat As EmbossFeature = shtComponentDefinition.Features.EmbossFeatures.Item(1)
	Dim aSideDef As ASideDefinition = flatPatt.ASideFace
	Dim tempSketches As New Dictionary(Of String, Object)
	Dim oSelectSet As SelectSet = partDoc.SelectSet
	' Loop through each row in the Excel file
	Dim row As Integer = 1
	Do While xlWorksheet.Cells(row, 1).Value IsNot Nothing
		Dim partName As String = xlWorksheet.Cells(row, 1).Value.ToString()
		Dim quantity As String = xlWorksheet.Cells(row, 2).Value.ToString()
		'Create a text user parameter in the part file that will be used for the emboss
		Parameter.UpdateAfterChange = True
		Parameter("PartName") = partName
		Logger.Info("PartName: " & partName)
		partDoc.Rebuild2(True)
		Dim dxfFileName As String = partName & "_" & quantity & ".dxf"
		Dim dxfFilePathOnly As String = Left(fileNameWithPath, fileNamePos)
		Dim dxfFilePath As String = dxfFilePathOnly & dxfFileName
		Try
			flatPatt.Edit()
		Catch
			' Handle possible error when editing the flat pattern
		End Try
		Dim faceWithMostEdges As Face = Nothing
		Dim faceEdgeCount As Double = 0
		For Each ASideFace As Face In flatPatt.Body.Faces'aSideDef.Faces
			If ASideFace.Edges.Count > faceEdgeCount Then
				faceWithMostEdges = ASideFace
				faceEdgeCount = ASideFace.Edges.Count
			End If
		Next
		Dim tempSketch As PlanarSketch = Nothing
		' Add sketch to selected face
		tempSketch = flatPatt.Sketches.Add(faceWithMostEdges, True)
		Dim tempSketchName As String = "TempDXF_Delete" & row
		tempSketch.Name = tempSketchName
		Dim tempInvFileName As String = partName & "_" & quantity
		Dim tempInvFileNamePath As String = dxfFilePathOnly & tempInvFileName & ".ipt"
		' Check if the file already exisits, and if it does just tack on a suffix
		If System.IO.File.Exists(tempInvFileNamePath) = True Then
			tempInvFileNamePath = tempInvFileNamePath.Replace(".", "_1.")
		End If
		logger.info("tempInvFileNamePath: " & tempInvFileNamePath)
		partDoc.SaveAs(tempInvFileNamePath, True)
		tempSketches.Add(tempInvFileNamePath, tempSketch)
		partDoc.Activate
		tempSketch.Delete
		flatPatt.ExitEdit
		' Proceed to the next row
		row += 1
	Loop
	' Create a temporary assembly to add the temp part files to, 
	' seems to be the only way to get the System.IO.StreamWriter to clear its memory between export
	Dim tempAssemblyDoc As AssemblyDocument = app.Documents.Add(DocumentTypeEnum.kAssemblyDocumentObject, , True)
	Dim docComponentDefinition As ComponentDefinition = tempAssemblyDoc.ComponentDefinition
	Dim assyDocFileNamePath As String = fileNameWithPath.Replace("ipt", "iam")
	' Check if the file already exisits, and if it does just tack on a suffix
	If System.IO.File.Exists(assyDocFileNamePath) = True Then
		assyDocFileNamePath = assyDocFileNamePath.Replace(".", "_1.")
	End If
	logger.info("assyDocFileNamePath: " & assyDocFileNamePath)
	tempAssemblyDoc.SaveAs(assyDocFileNamePath, False)
	tempAssemblyDoc.Activate
	PlaceParts(tempSketches, docComponentDefinition)
	' Need to close original sheetmetalpart to stop class error from happening
	partDoc.Close(False)
	' Close the workbook without saving
	xlWorkbook.Close(False)
	' Quit Excel
	xlApp.Quit()
	' Clean up
	ReleaseObject(xlWorksheet)
	ReleaseObject(xlWorkbook)
	ReleaseObject(xlApp)
	MessageBox.Show("You will now need to Run the Export DXF's rule from this Assembly!", "Finished", _
	MessageBoxButtons.OK, MessageBoxIcon.Information)
End Sub

Public Sub PlaceParts(tempSketches, docComponentDefinition)
	Dim fileCount As Integer = 0
	fileNameWithPath = ""
	intCounter = 0
	' Set a reference to the transient geometry object.
	Dim transGeometry As TransientGeometry = app.TransientGeometry
	' Create a matrix that will be translated/modified multiple times to place the occurrances in different locations
	Dim translatedGeometryMatrix As Matrix = transGeometry.CreateMatrix
		' Create the original matrix.  
	Dim transGeometryMatrix As Matrix = transGeometry.CreateMatrix
	'Get the plane from the assembly
	Dim YZPlane, XZPlane, XYPlane As WorkPlane
	Dim selectedOcc As ComponentOccurrence
	For Each pair As KeyValuePair(Of String, Object) In tempSketches
		Dim fileDlgSelectedFile As String = pair.Key
		logger.info("fileDlgSelectedFile: " & fileDlgSelectedFile)
		' translate this matrix to the new location
		Call transGeometryMatrix.SetTranslation(transGeometry.CreateVector(30, 30, 30))
		Call translatedGeometryMatrix.TransformBy(transGeometryMatrix)
		Dim oOccurrence As ComponentOccurrence = docComponentDefinition.Occurrences.Add(fileDlgSelectedFile, translatedGeometryMatrix)
	Next
End Sub

' Function to release objects
Private Sub ReleaseObject(ByVal obj As Object)
	Try
		Marshal.ReleaseComObject(obj)
		obj = Nothing
	Catch ex As Exception
		obj = Nothing
	Finally
		GC.Collect()
	End Try
End Sub

End Class

 

Then after that rule has create the assembly with the temp parts, from the assembly you can run this as an external rule:

' Check with JSC before modifying this rule
'[ ' Exports a dxf of the first sketch for every sheetmetaldocument
Sub Main
	app = ThisApplication
	If Not app.ActiveEditDocument.DocumentType = kAssemblyDocumentObject Then
		MessageBox.Show("This rule should only be run from Assembly files." & vbLf & _
		"Run rule only in .iam files!", "WARNING!", _
		MessageBoxButtons.OK, MessageBoxIcon.Warning)
		Exit Sub
	End If
	' Set a reference to the active edit document
	Dim assemblyDoc As AssemblyDocument = app.ActiveEditDocument
	If assemblyDoc.FullFileName = "" Then
		MessageBox.Show("Save Assembly Before Running Rule!" & vbLf & _
		"", "WARNING!", _
		MessageBoxButtons.OK, MessageBoxIcon.Warning)
		Exit Sub
	End If
	' For each document in assembly
	For Each tempInvDoc As Document In assemblyDoc.AllReferencedDocuments
		' shouldnt really need this as is a brand new assembly with only sheet metal parts
		If tempInvDoc.ComponentDefinition.Type = kSheetMetalComponentDefinitionObject Then
			Dim fileNameWithPath As String = tempInvDoc.FullDocumentName
			Dim fileNamePos As Long = InStrRev(fileNameWithPath, "\", -1)
			Dim dxfFileNameWithPath As String = fileNameWithPath.Replace("ipt", "dxf")
			Dim tempInvcompDef As SheetMetalComponentDefinition = tempInvDoc.ComponentDefinition
			Dim tempInvflatPatt As FlatPattern = tempInvcompDef.FlatPattern
			app.Documents.Open(fileNameWithPath, True)
			tempInvDoc.Activate
			Try
				tempInvflatPatt.Edit()
			Catch ex As Exception
				' Handle possible error when editing the flat pattern
				Logger.Info("unable to edit flat pattern" & ex.Message)
			End Try
			Dim tempInvSketch As PlanarSketch = tempInvflatPatt.Sketches.Item(1)
			app.ActiveView.Update()
			' Check if the file already exisits, and if it does just tack on a suffix
			If System.IO.File.Exists(dxfFileNameWithPath) = True Then
				dxfFileNameWithPath = dxfFileNameWithPath.Replace(".", "_1.")
			End If
			' Write sketch data to a DXF file
			tempInvSketch.DataIO.WriteDataToFile("DXF", dxfFileNameWithPath)
	        Try
	            tempInvflatPatt.ExitEdit()
	        Catch ex As Exception
	            Logger.Info("Error exiting flat pattern edit mode: " & ex.Message)
	        End Try
		End If
	Next
	MessageBox.Show("Rule Complete, You're Welcome!", "Finished", _
	MessageBoxButtons.OK, MessageBoxIcon.Information)
End Sub ']j

 

Hopefully that gets the job done,

 

James

0 Likes