openxml 操作doc文档

byte[] byteArray = File.ReadAllBytes("C:\\test.docm");

 

                using (MemoryStream stream = new MemoryStream())

                {

                    stream.Write(byteArray, 0, (int)byteArray.Length);

                    //OpenXML bookmarks

                    using (WordprocessingDocument doc = WordprocessingDocument.Open(stream, true))

                    {

                      

                        #region " 处理正文的bookmark"

                        foreach (BookmarkStart bookmark in doc.MainDocumentPart.RootElement.Descendants<BookmarkStart>())

                        {

                            for (int i = 0; i < mapBookmarks.Length; i++)

                            {

                                System.Data.DataTable dt = buliDS.Tables[mapBookmarks[i].TableName];

                                if (mapBookmarks[i].BookmarkName == bookmark.Name)

                                {

                                    var option = mapBookmarks[i];

                                    Run bkText = bookmark.NextSibling<Run>();

                                    DocumentFormat.OpenXml.OpenXmlElement elem = bookmark.NextSibling();

 

                                    #region replace values

                                    switch (option.Type)

                                    {

                                        case BookmarkType.None:

                                            break;

                                        case BookmarkType.Value:

                                            string val = "";

                                            switch (option.Source)

                                            {

                                                case DataSource.None:

                                                    break;

                                                case DataSource.Public:

                                                    //数据从界面输入

                                                    try

                                                    {

                                                        val = publdic[mapBookmarks[i].Key].ToString();

                                                    }

                                                    catch (Exception ex)

                                                    {

                                                        val = "";

                                                    }

                                                    bkText.GetFirstChild<Text>().Text = val;

                                                    break;

                                                case DataSource.Confirmation:

                                                    if (mapBookmarks[i].TableName != null)

                                                    {

                                                        try

                                                        {

                                                            //数据从数据源中拿

                                                            //buliDS.Tables[mapBookmarks[i].TableName] 拿到对应的表。Rows[0][mapBookmarks[i].Key] 拿到实际对应key的数据

                                                            string tabName = mapBookmarks[i].TableName;

 

                                                            if (dt.Rows.Count > 0)

                                                            {

                                                                //确定当前操作的是那一条confromation数据(下面一句,不懂请查看datatable的select方法)

                                                                DataRow[] dr = dt.Select(ShellForm.columnsName.BatchNo_Key + "  = " + batchNo + " AND " + ShellForm.columnsName.SeqNo_Key + " = " + seqNo);

                                                                if (dr.Length > 0)

                                                                {

                                                                    try

                                                                    {

                                                                        val = dr[0][mapBookmarks[i].Key].ToString();

                                                                    }

                                                                    catch (Exception ex)

                                                                    {

                                                                        val = "";

                                                                    }

                                                                }

                                                            }

 

                                                            bkText.GetFirstChild<Text>().Text = val;

                                                        }

                                                        catch (Exception ex)

                                                        {

                                                            Console.WriteLine("Confirmation:" + ex);

                                                        }

                                                    }

                                                    break;

                                                default:

                                                    break;

                                            }

                                            elem = elem.NextSibling();

                                            while (elem != null && !(elem is BookmarkEnd))

                                            {

                                                DocumentFormat.OpenXml.OpenXmlElement nextElem = elem.NextSibling();

                                                elem.Remove();

                                                elem = nextElem;

                                            }

                                            break;

                                        case BookmarkType.Table:

                                            string tableName = mapBookmarks[i].TableName;

 

                                            if (mapBookmarks[i].TableName != null)

                                            {

                                                try

                                                {

                                                    if (bookmark.Name == "其他事项")

                                                    {

                                                        try

                                                        {

                                                            string valStr = "";

                                                            DataRow[] dr = dt.Select(ShellForm.columnsName.BatchNo_Key + "  = " + batchNo + " AND " + ShellForm.columnsName.SeqNo_Key + " = " + seqNo);

                                                            for (int rowIndex = 0; rowIndex < dr.Length; rowIndex++)

                                                            {

                                                                foreach (var item1 in mapBookmarks[i].TableDataFormat)

                                                                {

                                                                    try

                                                                    {

                                                                        valStr += dr[rowIndex][item1.Key].ToString() + "    ";

                                                                    }

                                                                    catch (Exception ex)

                                                                    {

                                                                        valStr += "";

                                                                    }

                                                                }

                                                            }

                                                            bookmark.Parent.Parent.ReplaceChild(new Paragraph(new Run(new Text(valStr))), bookmark.Parent);

                                                        }

                                                        catch (Exception ex)

                                                        {

                                                            logger.Error(string.Format("其他事项(SpeedProgress) 异常. ex:{0}", ex));

                                                        }

                                                    }

                                                    else

                                                    {

 

                                                        int index = 0;

                                                        foreach (var item in bookmark.Parent.Parent.ChildElements)

                                                        {

                                                            if (item.LocalName == "tbl")

                                                            {

                                                                try

                                                                {

                                                                    if (bookmark.Parent.Parent.ElementAt(index + 1).InnerText == ("@" + bookmark.Name))

                                                                    {

                                                                        if (dt.Rows.Count > 0)

                                                                        {

                                                                            DataRow[] dr = dt.Select(ShellForm.columnsName.BatchNo_Key + "  = " + batchNo + " AND " + ShellForm.columnsName.SeqNo_Key + " = " + seqNo);

                                                                            if (dr.Length > 0)

                                                                            {

                                                                                //if (dt.Rows.Count > 0)

                                                                                //{

                                                                                for (int rowIndex = 0; rowIndex < dr.Length; rowIndex++)

                                                                                {

                                                                                    筛选和当前batchno和seqno对应的数据

                                                                                    //string dtKey = dt.Rows[rowIndex][ShellForm.columnsName.BatchNo_Key].ToString() + dt.Rows[rowIndex][ShellForm.columnsName.SeqNo_Key].ToString();

                                                                                    locKey 为选中数据时,对应模板和batchno和seq的对应的key

                                                                                    //if (dtKey == locKey)

                                                                                    //{

                                                                                    TableRow tr = new TableRow();

                                                                                    int tcIndex = 1;

                                                                                    foreach (var item1 in mapBookmarks[i].TableDataFormat)

                                                                                    {

                                                                                        // Create a cell.

                                                                                        TableCell tc1 = new TableCell();

 

                                                                                        //Properties

                                                                                        RunProperties runProperty = new RunProperties();

                                                                                        RunFonts runFont = new RunFonts();

                                                                                        runFont.Ascii = "Verdana";

                                                                                        runFont.HighAnsi = "Verdana";

                                                                                        runFont.EastAsia = "华文细黑";

 

                                                                                        FontSize newSize = new FontSize();

                                                                                        newSize.Val = "16";

                                                                                        ParagraphProperties paragraphProperty = new ParagraphProperties(new Justification() { Val = JustificationValues.Center });

                                                                                        paragraphProperty.KeepNext = new KeepNext();

                                                                                        paragraphProperty.KeepLines = new KeepLines();

 

                                                                                        runProperty.Append(runFont);

                                                                                        runProperty.Append(newSize);

 

                                                                                        // Run

                                                                                        Run newRun = new Run();

                                                                                        newRun.Append(runProperty);

                                                                                        newRun.Append(new Text(dr[rowIndex][item1.Key].ToString()));

 

                                                                                        // Specify the table cell content.

                                                                                        tc1.Append(paragraphProperty);

                                                                                        tc1.Append(new Paragraph(newRun));

 

 

                                                                                        tc1.TableCellProperties = ((item.LastChild as TableRow).ChildElements[tcIndex] as TableCell).TableCellProperties.Clone() as TableCellProperties;

                                                                                        // Append the table cell to the table row.

                                                                                        tr.Append(tc1);

 

                                                                                        tcIndex++;

                                                                                    }

                                                                                    tr.TableRowProperties = new TableRowProperties();

                                                                                    item.Append(tr);

                                                                                }

 

                                                                                //}

                                                                                // }

                                                                            }

                                                                            else

                                                                            {

                                                                                AddBlankRows(item, mapBookmarks, i);

                                                                            }

                                                                        }

                                                                        else

                                                                        {

                                                                            AddBlankRows(item, mapBookmarks, i);

                                                                        }

                                                                    }

                                                                }

                                                                catch (Exception ex)

                                                                {

                                                                    logger.Error(string.Format("tbl(SpeedProgress). ex:{0}", ex));

                                                                }

                                                            }

                                                            index++;

                                                        }

 

                                                    }

                                                }

                                                catch (Exception ex)

                                                {

                                                    Console.WriteLine("Table:" + ex);

                                                    logger.Error(string.Format("Table. BatchNo:{0} SeqNo:{1}. ex:{2}", batchNo, seqNo, ex));

                                                }

                                            }

                                            while (elem != null && !(elem is BookmarkEnd))

                                            {

                                                DocumentFormat.OpenXml.OpenXmlElement nextElem = elem.NextSibling();

                                                elem.Remove();

                                                elem = nextElem;

                                            }

                                            break;

                                        case BookmarkType.Barcode:

                                            try

                                            {

                                                string BarcodePath = "";

                                                BarcodePath = BulidBarCode(buliDS.Tables[ShellForm.columnsName.CSR], BulidTempList[locKey]);

 

                                                MainDocumentPart BarcodePart = doc.MainDocumentPart;

                                                ImagePart BarcodeImagePart = BarcodePart.AddImagePart(ImagePartType.Png);

                                                using (FileStream BarcodeStream = new FileStream(BarcodePath, FileMode.Open))

                                                {

                                                    BarcodeImagePart.FeedData(BarcodeStream);

                                                }

                                                var BarcodeElement = ImageElement(doc.MainDocumentPart.GetIdOfPart(BarcodeImagePart), 1300000, 590000);

                                                bookmark.Parent.Parent.ReplaceChild(new Paragraph(BarcodeElement), bookmark.Parent);

 

                                                while (elem != null && !(elem is BookmarkEnd))

                                                {

                                                    DocumentFormat.OpenXml.OpenXmlElement nextElem = elem.NextSibling();

                                                    elem.Remove();

                                                    elem = nextElem;

                                                }

                                            }

                                            catch (Exception ex)

                                            {

                                                ShowingProcessMsg(string.Format("异常:Barcode;exMessage:{0}\n", ex.Message));

                                            }

                                            break;

                                        case BookmarkType.QRcode:

 

                                            try

                                            {

 

                                                string QRcodePath = "";

                                                QRcodePath = BulidQRCode(buliDS.Tables[ShellForm.columnsName.CSR], BulidTempList[locKey]);

 

                                                MainDocumentPart QRcodePart = doc.MainDocumentPart;

                                                ImagePart QRcodeImagePart = QRcodePart.AddImagePart(ImagePartType.Jpeg);

                                                using (FileStream QRcodeStream = new FileStream(QRcodePath, FileMode.Open))

                                                {

                                                    QRcodeImagePart.FeedData(QRcodeStream);

                                                }

                                                var QRcodeElement = ImageElement(doc.MainDocumentPart.GetIdOfPart(QRcodeImagePart), 800000, 800000);

                                                // add the image element to body, the element should be in a Run.

 

                                                //bookmark.Parent.InsertAfter<Run>(new Run(QRcodeElement), bookmark);

                                                //bookmark.Parent.InsertBefore<Run>(new Run(QRcodeElement), bookmark);

                                                //doc.MainDocumentPart.Document.Body.InsertBefore<Run>(new Run (QRcodeElement),bookmark);

                                                //doc.MainDocumentPart.Document.Body.AppendChild(new Paragraph(new Run(QRcodeElement)));

                                                bookmark.Parent.Parent.ReplaceChild(new Paragraph(QRcodeElement), bookmark.Parent);

                                                while (elem != null && !(elem is BookmarkEnd))

                                                {

                                                    DocumentFormat.OpenXml.OpenXmlElement nextElem = elem.NextSibling();

                                                    elem.Remove();

                                                    elem = nextElem;

                                                }

                                            }

                                            catch (Exception ex)

                                            {

                                                ShowingProcessMsg(string.Format("异常:QRcode;exMessage:{0}\n", ex.Message));

                                            }

 

                                            break;

                                        default:

                                            break;

                                    }

                                    #endregion

 

 

                                    break;

                                }

 

                            }

                        }

                        #endregion

                        doc.Close();

                    }

                    File.WriteAllBytes(tempFileName, stream.ToArray());

                }

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
OpenXML 是一种基于 XML 的文件格式,可以用于创建和编辑 Microsoft Office 文档。在 Microsoft Word 中,可以将 OpenXML 格式的文档转换为流文档(FlowDocument),从而实现文档内容的显示和编辑等功能。 以下是将 OpenXML 格式的 Word 文档转换为流文档的示例代码: ```csharp using System; using System.IO; using System.Windows.Documents; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Wordprocessing; // 打开 OpenXML 格式的 Word 文档 using (WordprocessingDocument wordDoc = WordprocessingDocument.Open("docxFile.docx", false)) { // 获取 Word 文档的 MainDocumentPart MainDocumentPart mainPart = wordDoc.MainDocumentPart; // 创建流文档 FlowDocument flowDoc = new FlowDocument(); // 遍历 Word 文档中的段落 foreach (Paragraph paragraph in mainPart.Document.Body.Elements<Paragraph>()) { // 创建流文档中的段落 Paragraph flowParagraph = new Paragraph(); // 遍历 Word 文档中的 Run foreach (Run run in paragraph.Elements<Run>()) { // 创建流文档中的 Run Run flowRun = new Run(run.InnerText); // 复制 Run 的属性到流文档中的 Run flowRun.FontStyle = run.RunProperties.Italic ? FontStyles.Italic : FontStyles.Normal; flowRun.FontWeight = run.RunProperties.Bold ? FontWeights.Bold : FontWeights.Normal; flowRun.FontSize = run.RunProperties.FontSize.Value; flowRun.Foreground = new System.Windows.Media.SolidColorBrush(run.RunProperties.Color.Value); // 将流文档中的 Run 添加到流文档中的段落中 flowParagraph.Inlines.Add(flowRun); } // 将流文档中的段落添加到流文档中 flowDoc.Blocks.Add(flowParagraph); } // 将流文档保存到文件中 using (FileStream fs = new FileStream("flowDoc.xaml", FileMode.Create)) { XamlWriter.Save(flowDoc, fs); } } ``` 在上述示例代码中,我们首先打开一个 OpenXML 格式的 Word 文档。然后,我们创建一个流文档,并获取 Word 文档的 MainDocumentPart。接下来,我们遍历 Word 文档中的段落和 Run,并创建对应的流文档中的段落和 Run。我们还复制了 Run 的属性到流文档中的 Run 中。最后,我们将流文档保存到文件中。 需要注意的是,在运行上述代码之前,需要先添加以下引用: - WindowsBase.dll - PresentationFramework.dll - DocumentFormat.OpenXml.dll 另外,需要使用 .NET Framework 3.0 或更高版本。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值