Sheet Custom Property – Write Sheet Custom Properties
Writes a list of custom properties to the specified Excel worksheet.
VB
Public Sub xlWriteSheetCustomProperties(sheet As Worksheet,
table As Data.DataTable,
Optional RemoveAllBeforeWriting As Boolean = False)
If sheet Is Nothing Then Throw New ArgumentNullException(NameOf(sheet))
If table Is Nothing Then Throw New ArgumentNullException(NameOf(table))
Try
Dim props As CustomProperties = sheet.CustomProperties
If RemoveAllBeforeWriting Then
' Remove all existing custom properties
For i As Integer = props.Count To 1 Step -1
CType(props.Item(i), CustomProperty).Delete()
Next
End If
For Each row As DataRow In table.Rows
Dim name As String = row("Property").ToString()
Dim value As String = row("Value").ToString()
' Remove existing property with the same name (only if ReplaceAll is False)
If Not RemoveAllBeforeWriting Then
For i As Integer = props.Count To 1 Step -1
Dim prop As CustomProperty = CType(props.Item(i), CustomProperty)
If String.Equals(prop.Name, name, StringComparison.OrdinalIgnoreCase) Then
prop.Delete()
Exit For
End If
Next
End If
' Add the new property
props.Add(name, value)
Next
Catch ex As Exception
Throw New Exception("Error writing CustomProperties: " & ex.Message, ex)
End Try
End Sub