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

发布于 2025-01-22 15:58:52 字数 10424 浏览 4 评论 0原文

我正在研究一个旧的WebForms应用程序,并且正在尝试通过其中一个页面中的C#中的openxml创建Word文档。我正在尝试阅读来自SQL的数据以填充一张表格,我将在Word文档中创建的表格,以按照 http://www.ludovicperrichon.com/create-a-word-document-with-popenxml-and-and-c/

但是,每次我运行该代码会生成一个文档,该文档已损坏了一个文档并显示以下消息: “在此处输入图像描述”

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

我的示例代码在下面(不包括加载数据的数据表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();
                }

I am working on an old webforms application and I am trying to create a word document via the OpenXml in C# within one of the pages. I am trying to read in data from SQL to populate a table I will create in the word document by following the examples found at http://www.ludovicperrichon.com/create-a-word-document-with-openxml-and-c/

However, every time I run the code it produces a document that Word reports is corrupt and presents the following message: enter image description here

I cannot see what the issue is and I have been trying to find similar issues for a solution but I can only find mentions of a problem with the stream but this seems to be only when when reading an existing document to edit not creating a new one.

My example code is below (excluding the DataTable dt where the data is loaded, since that element works fine).

                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();
                }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

執念 2025-01-29 15:58:52

您正在使用错误的名称空间中的表格。而不是

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

使用

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

此其他表元素(单元格等)而不是使用它。

我建议使用 openxmlsdk 。如果您最终得到一个无效的文件,它将向您显示它出了什么问题。

You are using the tableelements from the wrong namespace. Instead of

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

use

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

This goes for all the other table elements (cells etc) as well.

I recommend using OpenXMLSDK. If you end up with an invalid file it will show you what's wrong with it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文