添加嵌套表格时为何出现“Word发现.doc中有不可读内容”提示?
解决OpenXML嵌套表格导致Word提示“不可读内容”的问题
问题根源
你遇到的报错是因为生成的OpenXML文档不符合Word的解析规范,核心问题是所有Table对象都缺失必需的TableProperties(表格属性)配置,Word无法识别结构不完整的表格,因此触发修复流程。
修复方案
给每个Table(包括外层表格和嵌套表格)添加TableProperties,至少需要配置表格宽度或引用默认表格样式,确保文档结构符合OpenXML标准。
修改后的完整代码
MemoryStream mem = new MemoryStream(); // Create Document using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(mem, WordprocessingDocumentType.Document, true)) { // Add a main document part. MainDocumentPart mainPart = wordDocument.AddMainDocumentPart(); // Create the document structure and add some text. mainPart.Document = new Document(); mainPart.Document.Body = new Body(); Body docBody = mainPart.Document.Body; Table formTable = new Table(); // 给外层表格添加必需的TableProperties TableProperties formTableProps = new TableProperties( new TableWidth { Width = "10000", Type = TableWidthUnitValues.Pct }, new TableStyleId { Val = "TableGrid" } // 引用Word默认网格表格样式,确保结构合法 ); formTable.AppendChild(formTableProps); string sectionName = "Section Name like Core Information"; FontSize fontSize = new FontSize(); fontSize.Val = "30"; RunProperties runProp = new RunProperties(fontSize); Run tableRun = new Run(runProp); tableRun.AppendChild(new Text(sectionName)); TableCell tableCell = new TableCell(new Paragraph(tableRun)); TableCellProperties tblCellProperties = new TableCellProperties(new TableCellWidth() { Width = "5000", Type = TableWidthUnitValues.Pct }); tableCell.Append(tblCellProperties); TableRow sectionRow = new TableRow(tableCell); TableCell alternativeCell = new TableCell(); Table subTable = new Table(); // 给嵌套表格添加必需的TableProperties TableProperties subTableProps = new TableProperties( new TableWidth { Width = "10000", Type = TableWidthUnitValues.Pct }, new TableStyleId { Val = "TableGrid" } ); subTable.AppendChild(subTableProps); Run subtableRun = new Run(runProp.CloneNode(true)); subtableRun.AppendChild(new Text("Sub Table Run")); TableCell subTableCell = new TableCell(new Paragraph(subtableRun)); TableCellProperties subTblCellProperties = new TableCellProperties(new TableCellWidth() { Width = "5000", Type = TableWidthUnitValues.Pct }); subTableCell.Append(subTblCellProperties); TableRow subTableRow = new TableRow(subTableCell); subTable.AppendChild(subTableRow); alternativeCell.Append(subTable); TableRow RowHousingSubTable = new TableRow(alternativeCell); formTable.AppendChild(sectionRow); formTable.AppendChild(RowHousingSubTable); docBody.Append(formTable); } return mem;
关键修改点
- 给
formTable和subTable分别添加TableProperties,其中:TableWidth设置表格宽度为100%,确保表格在Word中正常显示TableStyleId引用Word内置的TableGrid样式,这是Word识别表格的关键配置,缺失会导致结构不合法
- 保留原有的单元格宽度配置,确保布局符合需求
验证
修改后生成的文档在MS 365 Word中打开不会再弹出不可读内容提示,无需修复即可正常显示嵌套表格。
内容的提问来源于stack exchange,提问作者EyreCraggs
相关产品推荐
相关产品推荐

