OpenXML 创建 Word 文档总是损坏 C#

OpenXML Create Word Document always corrupt C#

我正在开发一个旧的 webforms 应用程序,我正在尝试通过其中一个页面中的 C# 中的 OpenXml 创建一个 word 文档。我正在尝试从 SQL 中读取数据以填充 table 我将按照 http://www.ludovicperrichon.com/create-a-word-document-with-openxml-and-c/

中的示例在 word 文档中创建

但是,每次我 运行 代码都会生成 Word 报告已损坏的文档并显示以下消息:

我看不出问题是什么,我一直在尝试寻找类似问题的解决方案,但我只能找到关于流问题的提及,但这似乎只有在阅读现有文档进行编辑时才会出现没有创建一个新的。

我的示例代码如下(不包括加载数据的 DataTable dt,因为该元素工作正常)。

                var header = "";

                using (var stream = new MemoryStream())
                {
                    using (var wordDoc = WordprocessingDocument.Create(stream, WordprocessingDocumentType.Document))
                    {
                        // Add a main document part.
                        MainDocumentPart mainPart = wordDoc.AddMainDocumentPart();

                        // Create the document structure and add some text.
                        mainPart.Document = new Document();
                        Body docBody = new Body();
                        mainPart.Document.Body = docBody;

                        // Load study plan and build word table to hold data
                        // Create an empty table.
                        var table = new DocumentFormat.OpenXml.Drawing.Table();

                        // Create a TableProperties object and specify its border information.
                        TableProperties tblProp = new TableProperties(
                            new TableBorders(
                                new TopBorder()
                                {
                                    Val =
                                    new EnumValue<BorderValues>(BorderValues.Dashed),
                                    Size = 24
                                },
                                new BottomBorder()
                                {
                                    Val =
                                    new EnumValue<BorderValues>(BorderValues.Dashed),
                                    Size = 24
                                },
                                new LeftBorder()
                                {
                                    Val =
                                    new EnumValue<BorderValues>(BorderValues.Dashed),
                                    Size = 24
                                },
                                new RightBorder()
                                {
                                    Val =
                                    new EnumValue<BorderValues>(BorderValues.Dashed),
                                    Size = 24
                                },
                                new InsideHorizontalBorder()
                                {
                                    Val =
                                    new EnumValue<BorderValues>(BorderValues.Dashed),
                                    Size = 24
                                },
                                new InsideVerticalBorder()
                                {
                                    Val =
                                    new EnumValue<BorderValues>(BorderValues.Dashed),
                                    Size = 24
                                }
                            )
                        );

                        // Append the TableProperties object to the empty table.
                        table.AppendChild<TableProperties>(tblProp);

                        // Add header row
                        // Create a row.
                        var hr = new DocumentFormat.OpenXml.Drawing.TableRow();

                        // Create a cell.
                        var hc1 = new DocumentFormat.OpenXml.Drawing.TableCell();

                        // Specify the width property of the table cell.
                        hc1.Append(new TableCellProperties(
                            new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "2400" }));

                        // Specify the table cell content.
                        hc1.Append(new Paragraph(new Run(new Text("Start Date"))));

                        // Append the table cell to the table row.
                        hr.Append(hc1);

                        // Create a cell
                        var hc2 = new DocumentFormat.OpenXml.Drawing.TableCell();

                        hc2.Append(new TableCellProperties(
                        new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "2400" }));

                        hc2.Append(new Paragraph(new Run(new Text("End Date"))));

                        // Append the table cell to the table row.
                        hr.Append(hc2);

                        // Create a cell
                        var hc3 = new DocumentFormat.OpenXml.Drawing.TableCell();

                        hc3.Append(new TableCellProperties(
                            new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "2400" }));

                        hc3.Append(new Paragraph(new Run(new Text("Type"))));

                        // Append the table cell to the table row.
                        hr.Append(hc3);

                        // Create a cell
                        var hc4 = new DocumentFormat.OpenXml.Drawing.TableCell();

                        hc4.Append(new TableCellProperties(
                            new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "2400" }));

                        hc4.Append(new Paragraph(new Run(new Text("Status"))));

                        // Append the table cell to the table row.
                        hr.Append(hc4);

                        // Create a cell
                        var hc5 = new DocumentFormat.OpenXml.Drawing.TableCell();

                        hc5.Append(new TableCellProperties(
                            new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "2400" }));

                        hc5.Append(new Paragraph(new Run(new Text("Description"))));

                        // Append the table cell to the table row.
                        hr.Append(hc5);

                        // Append the table row to the table.
                        table.Append(hr);

                        // Add data rows
                        for (var i = 0; i < dt.Rows.Count; i++)
                        {
                            // Create a row.
                            var tr = new DocumentFormat.OpenXml.Drawing.TableRow();

                            // Create a cell.
                            var tc1 = new DocumentFormat.OpenXml.Drawing.TableCell();

                            // Specify the width property of the table cell.
                            tc1.Append(new TableCellProperties(
                                new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "2400" }));

                            // Specify the table cell content.
                            tc1.Append(new Paragraph(new Run(new Text(dt.Rows[i]["start"].ToString()))));

                            // Append the table cell to the table row.
                            tr.Append(tc1);

                            //Create a cell
                            var tc2 = new DocumentFormat.OpenXml.Drawing.TableCell();

                            tc2.Append(new TableCellProperties(
                                new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "2400" }));

                            tc2.Append(new Paragraph(new Run(new Text(dt.Rows[i]["end"].ToString()))));

                            //Append the table cell to the table row.
                            tr.Append(tc2);

                            ///Create a cell
                            var tc3 = new DocumentFormat.OpenXml.Drawing.TableCell();

                            tc3.Append(new TableCellProperties(
                                new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "2400" }));

                            tc3.Append(new Paragraph(new Run(new Text(dt.Rows[i]["type"].ToString()))));

                            //Append the table cell to the table row.
                            tr.Append(tc3);

                            // Create a cell
                            var tc4 = new DocumentFormat.OpenXml.Drawing.TableCell();

                            tc4.Append(new TableCellProperties(
                                new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "2400" }));

                            tc4.Append(new Paragraph(new Run(new Text(dt.Rows[i]["status"].ToString()))));

                            //Append the table cell to the table row.
                            tr.Append(tc4);

                            //Create a cell
                            var tc5 = new DocumentFormat.OpenXml.Drawing.TableCell();

                            tc5.Append(new TableCellProperties(
                                new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "2400" }));

                            tc5.Append(new Paragraph(new Run(new Text(dt.Rows[i]["description"].ToString()))));

                            //Append the table cell to the table row.
                            tr.Append(tc5);

                            //Append the table row to the table.
                            table.Append(tr);
                        }

                        //Append the table to the document.                        
                        wordDoc.MainDocumentPart.Document.Body.Append(table);

                        header = "attachment;filename=" + DateTime.Today.ToString("dd/MM/yyyy") + student.Replace(" ", "_") + "_study_plan.docx";
                    }

                    Context.Response.AppendHeader("Content-Disposition", header);
                    stream.Position = 0;
                    stream.CopyTo(Context.Response.OutputStream);
                    Context.Response.Flush();
                    Context.Response.End();
                }

您正在使用来自错误命名空间的 table 元素。而不是

var table = new DocumentFormat.OpenXml.Drawing.Table();

使用

var table = new DocumentFormat.OpenXml.Wordprocessing.Table();

这也适用于所有其他 table 元素(单元格等)。

我推荐使用 OpenXMLSDK。如果您最终得到一个无效文件,它会告诉您它有什么问题。