/// <summary> /// 获取Word文档结构图 /// </summary> /// <param name="FilePath">文档路径</param> private void G(string FilePath) { object missing = System.Reflection.Missing.Value; object FileName = FilePath;//@"E:学习试验项目ReadFromWordDoctest.doc"; object readOnly = true; object isVisible = false; app = new word.Application(); doc = app.Documents.Open(ref FileName, ref missing, ref readOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref isVisible, ref missing, ref missing, ref missing, ref missing); object x = doc.GetCrossReferenceItems(Microsoft.Office.Interop.Word.WdReferenceType.wdRefTypeHeading); Array strs = (Array)x; int pid = 0; int id = 0; DataTable dt = new DataTable("dt"); //doc.Application.ScreenUpdating = false; dt.Columns.Add("SortFlag", typeof(int)); dt.Columns.Add("ParagraphIndex", typeof(int)); dt.Columns.Add("Name", typeof(string)); dt.Columns.Add("ID", typeof(int)); dt.Columns.Add("ParentID", typeof(int)); dt.Columns.Add("SectionNumber", typeof(int)); dt.Columns.Add("Level", typeof(string)); try { int UpLevel = 0; DataTable dtup = new DataTable("dtUP"); dtup.Columns.Add("SortFlag", typeof(int)); dtup.Columns.Add("ParagraphIndex", typeof(int)); dtup.Columns.Add("Name", typeof(string)); //SectionNumber dtup.Columns.Add("SectionNumber", typeof(int)); dtup.Columns.Add("ParentID", typeof(int)); dtup.Columns.Add("ID", typeof(int)); dtup.Columns.Add("Level", typeof(string)); DataRow drUP = dtup.NewRow(); for (int i = 0; i < strs.Length; i++) { object count = i + 1; string str = strs.GetValue(i + 1).ToString(); string strtrm = str.TrimStart(); DataRow dr = dt.NewRow(); dr["SortFlag"] = i + 1; dr["ParagraphIndex"] = i + 1; dr["Name"] = strtrm; int level = str.Length - strtrm.Length; dr["Level"] = level; if (level == 0) { dr["ParentID"] = 0; UpLevel = 0; object Heading = (int)Microsoft.Office.Interop.Word.WdGoToItem.wdGoToHeading; doc = new word.Document(); doc.Application.Selection.GoTo(ref Heading, ref missing, ref count, ref missing); dr["SectionNumber"] = doc.Application.Selection.get_Information(Microsoft.Office.Interop.Word.WdInformation.wdActiveEndSectionNumber); } else { if (level - UpLevel == 0) { dr["ParentID"] = drUP["ParentID"]; dr["SectionNumber"] = drUP["SectionNumber"]; } else if (level - UpLevel > 0) { dr["ParentID"] = drUP["ID"]; dr["SectionNumber"] = drUP["SectionNumber"]; } else { dr["ParentID"] = ParetnID(i - 1, dt, level)["ParentID"]; dr["SectionNumber"] = ParetnID(i - 1, dt, level)["SectionNumber"]; } } dt.Rows.Add(dr); UpLevel=level; drUP = dr; } }catch (Exception ex){throw ex;} } DataRow ParetnID(int rowindex, System.Data.DataTable dt, int level) { // object parentID = DBNull.Value; DataRow dr=dt.NewRow(); for (int i = rowindex; i >= 0; i--) { if (dt.Rows[i]["Level"].ToString() == level.ToString()) { dr = dt.Rows[i]; break; } } return dr; } }