文檔半島外圍網(wǎng)上直營>>E-iceblue中文文檔>>C#獲取Word文檔中內(nèi)容控件的別名、標簽和ID
                C#獲取Word文檔中內(nèi)容控件的別名、標簽和ID
內(nèi)容控件為您提供了一種設(shè)計文檔的方法。當(dāng)您向文檔添加內(nèi)容控件時,該控件由邊框、標題和可以向用戶提供說明的臨時文本標識。根據(jù)微軟的說法,內(nèi)容控件主要受益于兩個功能:
- 防止用戶編輯或刪除文檔的受保護部分。
- 將文檔或模板的部分內(nèi)容綁定到數(shù)據(jù)。您可以將內(nèi)容控件綁定到數(shù)據(jù)庫字段、.NET Framework 中的托管對象、存儲在文檔中的 XML 元素以及其他數(shù)據(jù)源。
因此,開發(fā)者在運行時處理內(nèi)容控件時,需要獲取內(nèi)容控件的屬性。本文說明如何通過 Spire.Doc 獲取所有控件及其屬性,包括別名、id 和標記。
首先,檢查包含六個按行和表格分布的內(nèi)容控件的測試文件。默認情況下,如果我們不點擊受保護的部分,控件的邊框和標題不會出現(xiàn)。
測試文件:
  
 
			
主要步驟:
第 1 步:創(chuàng)建一個新的 Word 文檔并加載測試文件。
第 2 步:創(chuàng)建兩個列表來存儲標簽,這些標簽分別以行和表的形式分布。在這里,每個內(nèi)容控件都將由標簽標識。
第 3 步:使用foreach語句獲取Word文檔中的所有標簽。
完整代碼:
static void Main(string[] args)
{
using (Document document = new Document(@"..\..\TestData\test.docx"))
{
StructureTags structureTags = GetAllTags(document);
List<StructureDocumentTagInline> tagInlines = structureTags.tagInlines;
string alias = tagInlines[0].SDTProperties.Alias;
decimal id = tagInlines[0].SDTProperties.Id;
string tag = tagInlines[0].SDTProperties.Tag;
List<StructureDocumentTag> tags = structureTags.tags;
alias = tags[0].SDTProperties.Alias;
id = tags[0].SDTProperties.Id;
tag = tags[0].SDTProperties.Tag;
}
}
static StructureTags GetAllTags(Document document)
{
StructureTags structureTags = new StructureTags();
foreach (Section section in document.Sections)
{
foreach (DocumentObject obj in section.Body.ChildObjects)
{
if (obj.DocumentObjectType == DocumentObjectType.Paragraph)
{
foreach (DocumentObject pobj in (obj as Paragraph).ChildObjects)
{
if (pobj.DocumentObjectType == DocumentObjectType.StructureDocumentTagInline)
{
structureTags.tagInlines.Add(pobj as StructureDocumentTagInline);
}
}
}
else if (obj.DocumentObjectType == DocumentObjectType.Table)
{
foreach (TableRow row in (obj as Table).Rows)
{
foreach (TableCell cell in row.Cells)
{
foreach (DocumentObject cellChild in cell.ChildObjects)
{
if (cellChild.DocumentObjectType == DocumentObjectType.StructureDocumentTag)
{
structureTags.tags.Add(cellChild as StructureDocumentTag);
}
else if (cellChild.DocumentObjectType == DocumentObjectType.Paragraph)
{
foreach (DocumentObject pobj in (cellChild as Paragraph).ChildObjects)
{
if (pobj.DocumentObjectType == DocumentObjectType.StructureDocumentTagInline)
{
structureTags.tagInlines.Add(pobj as StructureDocumentTagInline);
}
}
}
}
}
}
}
}
}
return structureTags;
}
public class StructureTags
{
List<StructureDocumentTagInline> m_tagInlines;
public List tagInlines
{
get
{
if (m_tagInlines == null)
m_tagInlines = new List();
return m_tagInlines;
}
set
{
m_tagInlines = value;
}
}
List<StructureDocumentTag> m_tags;
public List tags
{
get
{
if (m_tags == null)
m_tags = new List();
return m_tags;
}
set
{
m_tags = value;
}
}
}
效果截圖:
行中的內(nèi)容控件
  
 
			
表格中的內(nèi)容控件
  
 
			

 QQ交談
QQ交談 在線咨詢
在線咨詢 
                 
                
 渝公網(wǎng)安備
            50010702500608號
渝公網(wǎng)安備
            50010702500608號
             
            
 客服熱線
客服熱線