openxml对word的一些基本操作

/// <summary>
        /// 用于获取内容控件中指定的文档表
        /// </summary>
        /// <param name="oxe">内容控件</param>
        /// <param name="tag">标签</param>
        /// <returns></returns>
        public static Table DOC_TAB_GetTable(ref OpenXmlElement _oxe, string _tag)
        {
            SdtBlock _tBlock = _oxe.Descendants<SdtBlock>().Where(el => el.SdtProperties.GetFirstChild<Tag>().Val == _tag).Single();
            return _tBlock.Descendants<Table>().Single<Table>();
        }

        /// <summary>
        /// 获取内容控件表中的行数
        /// </summary>
        /// <param name="_tb">文档表对象</param>
        /// <returns></returns>
        public static int DOC_TAB_GetTableRowCount(Table _tb)
        {
            return _tb.Elements<TableRow>().Count();
        }

        /// <summary>
        /// 删除指定索引的行
        /// </summary>
        /// <param name="_tb">文档表对象</param>
        /// <param name="_index">删除行的索引</param>
        /// <returns></returns>
        public static bool DOC_TAB_DeleteTableRow(ref Table _tb, int _index)
        {
            if (!(_index >= 0 && _index < _tb.Elements<TableRow>().Count()))
            {
                return false;
            }
            try
            {
                _tb.RemoveChild(_tb.Elements<DocumentFormat.OpenXml.Wordprocessing.TableRow>().ElementAt(_index));
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
            return true;
        }

        /// <summary>
        /// 删除指定行 (重载)
        /// </summary>
        /// <param name="_tb">文档表</param>
        /// <param name="_tableRow">文档表行</param>
        /// <returns></returns>
        public static bool DOC_TAB_DeleteTableRow(ref Table _tb, ref TableRow _tableRow)
        {
            try
            {
                _tb.RemoveChild(_tableRow);
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 返回指定索引的行
        /// </summary>
        /// <param name="_tb">文档表对象</param>
        /// <param name="_index">指定行的索引</param>
        /// <returns></returns>
        public static TableRow DOC_TAB_GetTableRow(ref Table _tb, int _index)
        {
            try
            {
                return _tb.Elements<TableRow>().ElementAt(_index);
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
        }

        /// <summary>
        /// 返回复制后的文档表行
        /// </summary>
        /// <param name="_tableRow">要被复制的文档表行</param>
        /// <returns></returns>
        public static TableRow DOC_TAB_CloneTableRow(TableRow _tableRow)
        {
            return (TableRow)_tableRow.Clone();
        }

        /// <summary>
        /// 返回复制后的文档表行 (重载)
        /// </summary>
        /// <param name="_tb">文档表</param>
        /// <param name="_index">行所在索引</param>
        /// <returns></returns>
        public TableRow DOC_TAB_CloneTableRow(Table _tb, int _index)
        {
            return (TableRow)_tb.Elements<TableRow>().ElementAt(_index).Clone();
        }

        /// <summary>
        /// 向文档中指定的单元格添加数据
        /// </summary>
        /// <param name="_content">要添加的数据</param>
        /// <param name="_tableRow">文档行</param>
        /// <param name="_index">单元格的索引</param>
        public static void DOC_TAB_FillCellData(string _content, ref TableRow _tableRow, int _index)
        {
            TableCell _tableCell = _tableRow.Elements<TableCell>().ElementAt(_index);
            string[] _contentLine = System.Text.RegularExpressions.Regex.Split(_content, @"/r/n");
            DOC_TAB_ClearTextTableCell(ref _tableCell);

            for (int i = 0; i < _contentLine.Length; i++)
            {
                string _curCellData = _contentLine[i];
                //如果是第一行,则直接填充
                if (0 == i)
                {
                    if (_tableCell.Elements<Paragraph>().Count() > 0)
                    {
                        Paragraph _newParagraph = _tableCell.Elements<Paragraph>().Last();
                        if (_newParagraph.Elements<ParagraphProperties>().Count() > 0)
                        {
                            ParagraphProperties _paragraphProper = _newParagraph.Elements<ParagraphProperties>().First();

                            RunProperties _newRunProper = new RunProperties();
                            if (_paragraphProper.Elements<ParagraphMarkRunProperties>().Count() > 0)
                            {
                                ParagraphMarkRunProperties _paraMarkRunProper = _paragraphProper.Elements<ParagraphMarkRunProperties>().First();
                                for (int j = 0; j < _paraMarkRunProper.Elements().Count(); j++)
                                {
                                    _newRunProper.Append(_paraMarkRunProper.Elements().ElementAt(j).CloneNode(true));
                                }
                            }
                            else
                            {
                                _newRunProper.Append(new RunFonts() { Hint = FontTypeHintValues.EastAsia });
                            }
                            _newParagraph.Append(new Run(_newRunProper, new Text(_curCellData) { Space = "preserve" }));
                        }
                        else
                        {
                            _newParagraph.Append(new ParagraphMarkRunProperties(new RunFonts() { Hint = FontTypeHintValues.EastAsia }));
                            _newParagraph.Append(new Run(new RunProperties(new RunFonts() { Hint = FontTypeHintValues.EastAsia }), new Text(_curCellData) { Space = "preserve" }));
                        }
                    }
                    else
                    {
                        Paragraph _newParagraph = new Paragraph();
                        _newParagraph.Append(new ParagraphMarkRunProperties(new RunFonts().EastAsia));
                        _newParagraph.Append(new DocumentFormat.OpenXml.Wordprocessing.Run(new RunProperties(new RunFonts() { Hint = FontTypeHintValues.EastAsia }), new Text(_curCellData) { Space = "preserve" }));
                    }
                }
                else
                {
                    Paragraph _paragraph = _tableCell.Elements<Paragraph>().Last();
                    Paragraph _newParagraph = (Paragraph)_paragraph.Clone();
                    DocumentFormat.OpenXml.Wordprocessing.Run _newRun = _newParagraph.Elements<DocumentFormat.OpenXml.Wordprocessing.Run>().Last();
                    DocumentFormat.OpenXml.Wordprocessing.Text _newText = _newRun.Elements<DocumentFormat.OpenXml.Wordprocessing.Text>().Last();
                    _newText.Text = _curCellData;
                    _tableCell.Append(_newParagraph);
                }
            }
        }

        /// <summary>
        /// 在指定行后面添加新行
        /// </summary>
        /// <param name="_newRow">新行</param>
        /// <param name="_tb">文档表</param>
        /// <param name="_index">行索引</param>
        public static void DOC_TAB_InsertRowAfter(TableRow _newRow, ref Table _tb, int _index)
        {
            TableRow _tableRow = _tb.Elements<TableRow>().ElementAt(_index);
            _tb.InsertAfter<TableRow>(_newRow, _tableRow);
        }

        /// <summary>
        /// 在指定行前面添加新行
        /// </summary>
        /// <param name="_newRow">新行</param>
        /// <param name="_tb">文档表</param>
        /// <param name="_index">行索引</param>
        public static void DOC_TAB_InsertRowBefore(TableRow _newRow, ref Table _tb, int _index)
        {
            TableRow _tableRow = _tb.Elements<TableRow>().ElementAt(_index);
            _tb.InsertBefore<TableRow>(_newRow, _tableRow);
        }

        /// <summary>
        /// 清除单元格中的内容,但保留其格式
        /// </summary>
        /// <param name="_tableCell">单元格</param>
        public static void DOC_TAB_ClearTextTableCell(ref TableCell _tableCell)
        {
            for (int i = _tableCell.Elements<Paragraph>().Count() - 2; i >= 0; i--)
            {
                _tableCell.Elements<Paragraph>().ElementAt(i).Remove();
            }

            Paragraph _paragraph = _tableCell.Elements<Paragraph>().Single();
            foreach (Run _run in _paragraph.Elements<Run>())
            {
                _run.RemoveAllChildren();
            }
        }

        /// <summary>
        /// 用于插入文本内容
        /// </summary>
        /// <param name="_oxe">要填充内容的节点</param>
        /// <param name="_content">填充的内容</param>
        public static void DOC_TEXT_FillData(ref OpenXmlElement _oxe, string _content)
        {
            string _eType = _oxe.GetType().Name;
            switch (_eType)
            {
                case "SdtBlock":
                    Paragraph _paragraph = (Paragraph)_oxe.Descendants<Paragraph>().First().Clone();
                    Run _run = (Run)_paragraph.Elements<Run>().First().Clone();
                    _run.RemoveAllChildren<Text>();
                    _run.AppendChild<Text>(new Text(_content));
                    _paragraph.AppendChild<Run>(_run);

                    _oxe.RemoveAllChildren<Paragraph>();
                    _oxe.AppendChild<Paragraph>(_paragraph);
                    break;
                case "SdtRun":
                    SdtRun _sdtRun = (SdtRun)_oxe;
                    _sdtRun.SdtProperties.RemoveAllChildren<SdtPlaceholder>();

                    RunProperties _runPro = (RunProperties)_sdtRun.Elements<RunProperties>().Single().Clone();
                    Text _runText = new Text(_content);

                    Run _runAnother = _sdtRun.SdtContentRun.Elements<Run>().Single();
                    _runAnother.RemoveAllChildren();
                    _runAnother.AppendChild(_runPro);
                    _runAnother.AppendChild(_runText);
                    break;
                case "Run":
                    _oxe.RemoveAllChildren();
                    _oxe.AppendChild(new Text(_content));
                    break;
            }
        }

 

using System.Collections.Generic;
using System.Linq;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;

namespace openxml_word
{
    public static class WordStyleExtensions
    {
        public static string GetStyleIdFromStyleName(MainDocumentPart mainPart, string styleName)
        {
            StyleDefinitionsPart stylePart = mainPart.StyleDefinitionsPart;
            string styleId = stylePart.Styles.Descendants<StyleName>().Where(c => c.Val.Value.Equals(styleName))
                .Select(c => ((Style)c.Parent).StyleId).FirstOrDefault();
            return styleId ?? styleName;
        }

        public static IEnumerable<Paragraph> ParagraphByStyleName(this MainDocumentPart mainPart, string styleName)
        {
            string styleId = GetStyleIdFromStyleName(mainPart, styleName);
            IEnumerable<Paragraph> paraList = mainPart.Document.Descendants<Paragraph>().Where(p => IsParagraphInStyle(p, styleId));
            return paraList;
        }

        public static bool IsParagraphInStyle(Paragraph p, string styleId)
        {
            ParagraphProperties pPr = p.GetFirstChild<ParagraphProperties>();
            if (pPr != null)
            {
                ParagraphStyleId paraStyle = pPr.ParagraphStyleId;
                if (paraStyle != null)
                {
                    return paraStyle.Val.Value.Equals(styleId);
                }
            }
            return false;
        }

        public static IEnumerable<Run> RunByStyleName(this MainDocumentPart mainPart, string styleName)
        {
            string styleId = GetStyleIdFromStyleName(mainPart, styleName);
            IEnumerable<Run> runList = mainPart.Document.Descendants<Run>().Where(r => IsRunInStyle(r, styleId));
            return runList;
        }

        public static bool IsRunInStyle(Run p, string styleId)
        {
            RunProperties rPr = p.GetFirstChild<RunProperties>();
            if (rPr != null)
            {
                RunStyle runStyle = rPr.RunStyle;
                if (runStyle != null)
                {
                    return runStyle.Val.Value.Equals(styleId);
                }
            }
            return false;
        }
    }
}

  


  1 /// <summary>
  2         /// 用于获取内容控件中指定的文档表
  3         /// </summary>
  4         /// <param name="oxe">内容控件</param>
  5         /// <param name="tag">标签</param>
  6         /// <returns></returns>
  7         public static Table DOC_TAB_GetTable(ref OpenXmlElement _oxe, string _tag)
  8         {
  9             SdtBlock _tBlock = _oxe.Descendants<SdtBlock>().Where(el => el.SdtProperties.GetFirstChild<Tag>().Val == _tag).Single();
 10             return _tBlock.Descendants<Table>().Single<Table>();
 11         }
 12 
 13         /// <summary>
 14         /// 获取内容控件表中的行数
 15         /// </summary>
 16         /// <param name="_tb">文档表对象</param>
 17         /// <returns></returns>
 18         public static int DOC_TAB_GetTableRowCount(Table _tb)
 19         {
 20             return _tb.Elements<TableRow>().Count();
 21         }
 22 
 23         /// <summary>
 24         /// 删除指定索引的行
 25         /// </summary>
 26         /// <param name="_tb">文档表对象</param>
 27         /// <param name="_index">删除行的索引</param>
 28         /// <returns></returns>
 29         public static bool DOC_TAB_DeleteTableRow(ref Table _tb, int _index)
 30         {
 31             if (!(_index >= 0 && _index < _tb.Elements<TableRow>().Count()))
 32             {
 33                 return false;
 34             }
 35             try
 36             {
 37                 _tb.RemoveChild(_tb.Elements<DocumentFormat.OpenXml.Wordprocessing.TableRow>().ElementAt(_index));
 38             }
 39             catch (Exception e)
 40             {
 41                 throw new Exception(e.Message);
 42             }
 43             return true;
 44         }
 45 
 46         /// <summary>
 47         /// 删除指定行 (重载)
 48         /// </summary>
 49         /// <param name="_tb">文档表</param>
 50         /// <param name="_tableRow">文档表行</param>
 51         /// <returns></returns>
 52         public static bool DOC_TAB_DeleteTableRow(ref Table _tb, ref TableRow _tableRow)
 53         {
 54             try
 55             {
 56                 _tb.RemoveChild(_tableRow);
 57                 return true;
 58             }
 59             catch
 60             {
 61                 return false;
 62             }
 63         }
 64 
 65         /// <summary>
 66         /// 返回指定索引的行
 67         /// </summary>
 68         /// <param name="_tb">文档表对象</param>
 69         /// <param name="_index">指定行的索引</param>
 70         /// <returns></returns>
 71         public static TableRow DOC_TAB_GetTableRow(ref Table _tb, int _index)
 72         {
 73             try
 74             {
 75                 return _tb.Elements<TableRow>().ElementAt(_index);
 76             }
 77             catch (Exception e)
 78             {
 79                 throw new Exception(e.Message);
 80             }
 81         }
 82 
 83         /// <summary>
 84         /// 返回复制后的文档表行
 85         /// </summary>
 86         /// <param name="_tableRow">要被复制的文档表行</param>
 87         /// <returns></returns>
 88         public static TableRow DOC_TAB_CloneTableRow(TableRow _tableRow)
 89         {
 90             return (TableRow)_tableRow.Clone();
 91         }
 92 
 93         /// <summary>
 94         /// 返回复制后的文档表行 (重载)
 95         /// </summary>
 96         /// <param name="_tb">文档表</param>
 97         /// <param name="_index">行所在索引</param>
 98         /// <returns></returns>
 99         public TableRow DOC_TAB_CloneTableRow(Table _tb, int _index)
100         {
101             return (TableRow)_tb.Elements<TableRow>().ElementAt(_index).Clone();
102         }
103 
104         /// <summary>
105         /// 向文档中指定的单元格添加数据
106         /// </summary>
107         /// <param name="_content">要添加的数据</param>
108         /// <param name="_tableRow">文档行</param>
109         /// <param name="_index">单元格的索引</param>
110         public static void DOC_TAB_FillCellData(string _content, ref TableRow _tableRow, int _index)
111         {
112             TableCell _tableCell = _tableRow.Elements<TableCell>().ElementAt(_index);
113             string[] _contentLine = System.Text.RegularExpressions.Regex.Split(_content, @"/r/n");
114             DOC_TAB_ClearTextTableCell(ref _tableCell);
115 
116             for (int i = 0; i < _contentLine.Length; i++)
117             {
118                 string _curCellData = _contentLine[i];
119                 //如果是第一行,则直接填充
120                 if (0 == i)
121                 {
122                     if (_tableCell.Elements<Paragraph>().Count() > 0)
123                     {
124                         Paragraph _newParagraph = _tableCell.Elements<Paragraph>().Last();
125                         if (_newParagraph.Elements<ParagraphProperties>().Count() > 0)
126                         {
127                             ParagraphProperties _paragraphProper = _newParagraph.Elements<ParagraphProperties>().First();
128 
129                             RunProperties _newRunProper = new RunProperties();
130                             if (_paragraphProper.Elements<ParagraphMarkRunProperties>().Count() > 0)
131                             {
132                                 ParagraphMarkRunProperties _paraMarkRunProper = _paragraphProper.Elements<ParagraphMarkRunProperties>().First();
133                                 for (int j = 0; j < _paraMarkRunProper.Elements().Count(); j++)
134                                 {
135                                     _newRunProper.Append(_paraMarkRunProper.Elements().ElementAt(j).CloneNode(true));
136                                 }
137                             }
138                             else
139                             {
140                                 _newRunProper.Append(new RunFonts() { Hint = FontTypeHintValues.EastAsia });
141                             }
142                             _newParagraph.Append(new Run(_newRunProper, new Text(_curCellData) { Space = "preserve" }));
143                         }
144                         else
145                         {
146                             _newParagraph.Append(new ParagraphMarkRunProperties(new RunFonts() { Hint = FontTypeHintValues.EastAsia }));
147                             _newParagraph.Append(new Run(new RunProperties(new RunFonts() { Hint = FontTypeHintValues.EastAsia }), new Text(_curCellData) { Space = "preserve" }));
148                         }
149                     }
150                     else
151                     {
152                         Paragraph _newParagraph = new Paragraph();
153                         _newParagraph.Append(new ParagraphMarkRunProperties(new RunFonts().EastAsia));
154                         _newParagraph.Append(new DocumentFormat.OpenXml.Wordprocessing.Run(new RunProperties(new RunFonts() { Hint = FontTypeHintValues.EastAsia }), new Text(_curCellData) { Space = "preserve" }));
155                     }
156                 }
157                 else
158                 {
159                     Paragraph _paragraph = _tableCell.Elements<Paragraph>().Last();
160                     Paragraph _newParagraph = (Paragraph)_paragraph.Clone();
161                     DocumentFormat.OpenXml.Wordprocessing.Run _newRun = _newParagraph.Elements<DocumentFormat.OpenXml.Wordprocessing.Run>().Last();
162                     DocumentFormat.OpenXml.Wordprocessing.Text _newText = _newRun.Elements<DocumentFormat.OpenXml.Wordprocessing.Text>().Last();
163                     _newText.Text = _curCellData;
164                     _tableCell.Append(_newParagraph);
165                 }
166             }
167         }
168 
169         /// <summary>
170         /// 在指定行后面添加新行
171         /// </summary>
172         /// <param name="_newRow">新行</param>
173         /// <param name="_tb">文档表</param>
174         /// <param name="_index">行索引</param>
175         public static void DOC_TAB_InsertRowAfter(TableRow _newRow, ref Table _tb, int _index)
176         {
177             TableRow _tableRow = _tb.Elements<TableRow>().ElementAt(_index);
178             _tb.InsertAfter<TableRow>(_newRow, _tableRow);
179         }
180 
181         /// <summary>
182         /// 在指定行前面添加新行
183         /// </summary>
184         /// <param name="_newRow">新行</param>
185         /// <param name="_tb">文档表</param>
186         /// <param name="_index">行索引</param>
187         public static void DOC_TAB_InsertRowBefore(TableRow _newRow, ref Table _tb, int _index)
188         {
189             TableRow _tableRow = _tb.Elements<TableRow>().ElementAt(_index);
190             _tb.InsertBefore<TableRow>(_newRow, _tableRow);
191         }
192 
193         /// <summary>
194         /// 清除单元格中的内容,但保留其格式
195         /// </summary>
196         /// <param name="_tableCell">单元格</param>
197         public static void DOC_TAB_ClearTextTableCell(ref TableCell _tableCell)
198         {
199             for (int i = _tableCell.Elements<Paragraph>().Count() - 2; i >= 0; i--)
200             {
201                 _tableCell.Elements<Paragraph>().ElementAt(i).Remove();
202             }
203 
204             Paragraph _paragraph = _tableCell.Elements<Paragraph>().Single();
205             foreach (Run _run in _paragraph.Elements<Run>())
206             {
207                 _run.RemoveAllChildren();
208             }
209         }
210 
211         /// <summary>
212         /// 用于插入文本内容
213         /// </summary>
214         /// <param name="_oxe">要填充内容的节点</param>
215         /// <param name="_content">填充的内容</param>
216         public static void DOC_TEXT_FillData(ref OpenXmlElement _oxe, string _content)
217         {
218             string _eType = _oxe.GetType().Name;
219             switch (_eType)
220             {
221                 case "SdtBlock":
222                     Paragraph _paragraph = (Paragraph)_oxe.Descendants<Paragraph>().First().Clone();
223                     Run _run = (Run)_paragraph.Elements<Run>().First().Clone();
224                     _run.RemoveAllChildren<Text>();
225                     _run.AppendChild<Text>(new Text(_content));
226                     _paragraph.AppendChild<Run>(_run);
227 
228                     _oxe.RemoveAllChildren<Paragraph>();
229                     _oxe.AppendChild<Paragraph>(_paragraph);
230                     break;
231                 case "SdtRun":
232                     SdtRun _sdtRun = (SdtRun)_oxe;
233                     _sdtRun.SdtProperties.RemoveAllChildren<SdtPlaceholder>();
234 
235                     RunProperties _runPro = (RunProperties)_sdtRun.Elements<RunProperties>().Single().Clone();
236                     Text _runText = new Text(_content);
237 
238                     Run _runAnother = _sdtRun.SdtContentRun.Elements<Run>().Single();
239                     _runAnother.RemoveAllChildren();
240                     _runAnother.AppendChild(_runPro);
241                     _runAnother.AppendChild(_runText);
242                     break;
243                 case "Run":
244                     _oxe.RemoveAllChildren();
245                     _oxe.AppendChild(new Text(_content));
246                     break;
247             }
248         }
posted @ 2012-07-10 21:47  RyanCheng  阅读(2081)  评论(0编辑  收藏  举报