選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

Table.cs 130KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035
  1. /*************************************************************************************
  2. DocX – DocX is the community edition of Xceed Words for .NET
  3. Copyright (C) 2009-2016 Xceed Software Inc.
  4. This program is provided to you under the terms of the Microsoft Public
  5. License (Ms-PL) as published at http://wpftoolkit.codeplex.com/license
  6. For more features and fast professional support,
  7. pick up Xceed Words for .NET at https://xceed.com/xceed-words-for-net/
  8. ***********************************************************************************/
  9. using System;
  10. using System.Collections.Generic;
  11. using System.Linq;
  12. using System.Xml.Linq;
  13. using System.IO.Packaging;
  14. using System.IO;
  15. using System.Drawing;
  16. using System.Globalization;
  17. using System.Collections.ObjectModel;
  18. namespace Xceed.Words.NET
  19. {
  20. /// <summary>
  21. /// Represents a Table in a document.
  22. /// </summary>
  23. public class Table : InsertBeforeOrAfter
  24. {
  25. #region Private Members
  26. private Alignment _alignment;
  27. private AutoFit _autofit;
  28. private float[] _columnWidths;
  29. private TableDesign _design;
  30. /// <summary>
  31. /// The custom design\style to apply to this table.
  32. ///
  33. /// </summary>
  34. private string _customTableDesignName;
  35. private int _cachedColumnCount = -1;
  36. #endregion
  37. #region Public Properties
  38. /// <summary>
  39. /// Returns a list of all Paragraphs inside this container.
  40. /// </summary>
  41. ///
  42. public virtual List<Paragraph> Paragraphs
  43. {
  44. get
  45. {
  46. var paragraphs = new List<Paragraph>();
  47. foreach( Row r in Rows )
  48. paragraphs.AddRange( r.Paragraphs );
  49. return paragraphs;
  50. }
  51. }
  52. /// <summary>
  53. /// Returns a list of all Pictures in a Table.
  54. /// </summary>
  55. /// <example>
  56. /// Returns a list of all Pictures in a Table.
  57. /// <code>
  58. /// <![CDATA[
  59. /// // Create a document.
  60. /// using (DocX document = DocX.Load(@"Test.docx"))
  61. /// {
  62. /// // Get the first Table in a document.
  63. /// Table t = document.Tables[0];
  64. ///
  65. /// // Get all of the Pictures in this Table.
  66. /// List<Picture> pictures = t.Pictures;
  67. ///
  68. /// // Save this document.
  69. /// document.Save();
  70. /// }
  71. /// ]]>
  72. /// </code>
  73. /// </example>
  74. public List<Picture> Pictures
  75. {
  76. get
  77. {
  78. var pictures = new List<Picture>();
  79. foreach( Row r in Rows )
  80. {
  81. pictures.AddRange( r.Pictures );
  82. }
  83. return pictures;
  84. }
  85. }
  86. /// <summary>
  87. /// Get all of the Hyperlinks in this Table.
  88. /// </summary>
  89. /// <example>
  90. /// Get all of the Hyperlinks in this Table.
  91. /// <code>
  92. /// // Create a document.
  93. /// using (DocX document = DocX.Load(@"Test.docx"))
  94. /// {
  95. /// // Get the first Table in this document.
  96. /// Table t = document.Tables[0];
  97. ///
  98. /// // Get a list of all Hyperlinks in this Table.
  99. /// List&lt;Hyperlink&gt; hyperlinks = t.Hyperlinks;
  100. ///
  101. /// // Save this document.
  102. /// document.Save();
  103. /// }
  104. /// </code>
  105. /// </example>
  106. public List<Hyperlink> Hyperlinks
  107. {
  108. get
  109. {
  110. var hyperlinks = new List<Hyperlink>();
  111. foreach( Row r in Rows )
  112. {
  113. hyperlinks.AddRange( r.Hyperlinks );
  114. }
  115. return hyperlinks;
  116. }
  117. }
  118. /// <summary>
  119. /// Returns the number of rows in this table.
  120. /// </summary>
  121. public Int32 RowCount
  122. {
  123. get
  124. {
  125. return this.Xml.Elements( XName.Get( "tr", DocX.w.NamespaceName ) ).Count();
  126. }
  127. }
  128. /// <summary>
  129. /// Returns the number of columns in this table.
  130. /// </summary>
  131. public Int32 ColumnCount
  132. {
  133. get
  134. {
  135. if( this.RowCount == 0 )
  136. return 0;
  137. if( _cachedColumnCount == -1 )
  138. {
  139. foreach( var r in this.Rows )
  140. {
  141. _cachedColumnCount = Math.Max( _cachedColumnCount, r.ColumnCount );
  142. }
  143. }
  144. return _cachedColumnCount;
  145. }
  146. }
  147. /// <summary>
  148. /// Returns a list of rows in this table.
  149. /// </summary>
  150. public List<Row> Rows
  151. {
  152. get
  153. {
  154. var rows =
  155. (
  156. from r in Xml.Elements( XName.Get( "tr", DocX.w.NamespaceName ) )
  157. select new Row( this, Document, r )
  158. ).ToList();
  159. return rows;
  160. }
  161. }
  162. public Alignment Alignment
  163. {
  164. get
  165. {
  166. return _alignment;
  167. }
  168. set
  169. {
  170. string alignmentString = string.Empty;
  171. switch( value )
  172. {
  173. case Alignment.left:
  174. {
  175. alignmentString = "left";
  176. break;
  177. }
  178. case Alignment.both:
  179. {
  180. alignmentString = "both";
  181. break;
  182. }
  183. case Alignment.right:
  184. {
  185. alignmentString = "right";
  186. break;
  187. }
  188. case Alignment.center:
  189. {
  190. alignmentString = "center";
  191. break;
  192. }
  193. }
  194. XElement tblPr = Xml.Descendants( XName.Get( "tblPr", DocX.w.NamespaceName ) ).First();
  195. XElement jc = tblPr.Descendants( XName.Get( "jc", DocX.w.NamespaceName ) ).FirstOrDefault();
  196. jc?.Remove();
  197. jc = new XElement( XName.Get( "jc", DocX.w.NamespaceName ), new XAttribute( XName.Get( "val", DocX.w.NamespaceName ), alignmentString ) );
  198. tblPr.Add( jc );
  199. _alignment = value;
  200. }
  201. }
  202. /// <summary>
  203. /// Auto size this table according to some rule.
  204. /// </summary>
  205. public AutoFit AutoFit
  206. {
  207. get
  208. {
  209. return _autofit;
  210. }
  211. set
  212. {
  213. string tableAttributeValue = string.Empty;
  214. string columnAttributeValue = string.Empty;
  215. switch( value )
  216. {
  217. case AutoFit.ColumnWidth:
  218. {
  219. tableAttributeValue = "auto";
  220. columnAttributeValue = "dxa";
  221. // Disable "Automatically resize to fit contents" option
  222. var tblPr = Xml.Element( XName.Get( "tblPr", DocX.w.NamespaceName ) );
  223. if( tblPr != null )
  224. {
  225. var layout = tblPr.Element( XName.Get( "tblLayout", DocX.w.NamespaceName ) );
  226. if( layout == null )
  227. {
  228. tblPr.Add( new XElement( XName.Get( "tblLayout", DocX.w.NamespaceName ) ) );
  229. layout = tblPr.Element( XName.Get( "tblLayout", DocX.w.NamespaceName ) );
  230. }
  231. var type = layout.Attribute( XName.Get( "type", DocX.w.NamespaceName ) );
  232. if( type == null )
  233. {
  234. layout.Add( new XAttribute( XName.Get( "type", DocX.w.NamespaceName ), String.Empty ) );
  235. type = layout.Attribute( XName.Get( "type", DocX.w.NamespaceName ) );
  236. }
  237. type.Value = "fixed";
  238. }
  239. break;
  240. }
  241. case AutoFit.Contents:
  242. {
  243. tableAttributeValue = columnAttributeValue = "auto";
  244. break;
  245. }
  246. case AutoFit.Window:
  247. {
  248. tableAttributeValue = columnAttributeValue = "pct";
  249. break;
  250. }
  251. case AutoFit.Fixed:
  252. {
  253. tableAttributeValue = columnAttributeValue = "dxa";
  254. var tblPr = Xml.Element( XName.Get( "tblPr", DocX.w.NamespaceName ) );
  255. var tblLayout = tblPr.Element( XName.Get( "tblLayout", DocX.w.NamespaceName ) );
  256. if( tblLayout == null )
  257. {
  258. var tmp = tblPr.Element( XName.Get( "tblInd", DocX.w.NamespaceName ) ) ?? tblPr.Element( XName.Get( "tblW", DocX.w.NamespaceName ) );
  259. tmp.AddAfterSelf( new XElement( XName.Get( "tblLayout", DocX.w.NamespaceName ) ) );
  260. tmp = tblPr.Element( XName.Get( "tblLayout", DocX.w.NamespaceName ) );
  261. tmp.SetAttributeValue( XName.Get( "type", DocX.w.NamespaceName ), "fixed" );
  262. tmp = tblPr.Element( XName.Get( "tblW", DocX.w.NamespaceName ) );
  263. Double totalWidth = 0;
  264. foreach( Double columnWidth in ColumnWidths )
  265. {
  266. totalWidth += columnWidth;
  267. }
  268. tmp.SetAttributeValue( XName.Get( "w", DocX.w.NamespaceName ), totalWidth.ToString() );
  269. break;
  270. }
  271. else
  272. {
  273. var types = from d in Xml.Descendants()
  274. let type = d.Attribute( XName.Get( "type", DocX.w.NamespaceName ) )
  275. where ( d.Name.LocalName == "tblLayout" ) && type != null
  276. select type;
  277. foreach( XAttribute type in types )
  278. {
  279. type.Value = "fixed";
  280. }
  281. var tmp = tblPr.Element( XName.Get( "tblW", DocX.w.NamespaceName ) );
  282. Double totalWidth = 0;
  283. foreach( Double columnWidth in ColumnWidths )
  284. {
  285. totalWidth += columnWidth;
  286. }
  287. tmp.SetAttributeValue( XName.Get( "w", DocX.w.NamespaceName ), totalWidth.ToString() );
  288. break;
  289. }
  290. }
  291. }
  292. // Set table attributes
  293. var query = from d in Xml.Descendants()
  294. let type = d.Attribute( XName.Get( "type", DocX.w.NamespaceName ) )
  295. where ( d.Name.LocalName == "tblW" ) && type != null
  296. select type;
  297. foreach( XAttribute type in query )
  298. {
  299. type.Value = tableAttributeValue;
  300. }
  301. // Set column attributes
  302. query = from d in Xml.Descendants()
  303. let type = d.Attribute( XName.Get( "type", DocX.w.NamespaceName ) )
  304. where ( d.Name.LocalName == "tcW" ) && type != null
  305. select type;
  306. foreach( XAttribute type in query )
  307. {
  308. type.Value = columnAttributeValue;
  309. }
  310. _autofit = value;
  311. }
  312. }
  313. /// <summary>
  314. /// The design\style to apply to this table.
  315. /// </summary>
  316. public TableDesign Design
  317. {
  318. get
  319. {
  320. return _design;
  321. }
  322. set
  323. {
  324. XElement tblPr = Xml.Element( XName.Get( "tblPr", DocX.w.NamespaceName ) );
  325. XElement style = tblPr.Element( XName.Get( "tblStyle", DocX.w.NamespaceName ) );
  326. if( style == null )
  327. {
  328. tblPr.Add( new XElement( XName.Get( "tblStyle", DocX.w.NamespaceName ) ) );
  329. style = tblPr.Element( XName.Get( "tblStyle", DocX.w.NamespaceName ) );
  330. }
  331. XAttribute val = style.Attribute( XName.Get( "val", DocX.w.NamespaceName ) );
  332. if( val == null )
  333. {
  334. style.Add( new XAttribute( XName.Get( "val", DocX.w.NamespaceName ), "" ) );
  335. val = style.Attribute( XName.Get( "val", DocX.w.NamespaceName ) );
  336. }
  337. _design = value;
  338. if( _design == TableDesign.None )
  339. {
  340. if( style != null )
  341. style.Remove();
  342. }
  343. if( _design == TableDesign.Custom )
  344. {
  345. if( string.IsNullOrEmpty( _customTableDesignName ) )
  346. {
  347. _design = TableDesign.None;
  348. if( style != null )
  349. style.Remove();
  350. }
  351. else
  352. {
  353. val.Value = _customTableDesignName;
  354. }
  355. }
  356. else
  357. {
  358. switch( _design )
  359. {
  360. case TableDesign.TableNormal:
  361. val.Value = "TableNormal";
  362. break;
  363. case TableDesign.TableGrid:
  364. val.Value = "TableGrid";
  365. break;
  366. case TableDesign.LightShading:
  367. val.Value = "LightShading";
  368. break;
  369. case TableDesign.LightShadingAccent1:
  370. val.Value = "LightShading-Accent1";
  371. break;
  372. case TableDesign.LightShadingAccent2:
  373. val.Value = "LightShading-Accent2";
  374. break;
  375. case TableDesign.LightShadingAccent3:
  376. val.Value = "LightShading-Accent3";
  377. break;
  378. case TableDesign.LightShadingAccent4:
  379. val.Value = "LightShading-Accent4";
  380. break;
  381. case TableDesign.LightShadingAccent5:
  382. val.Value = "LightShading-Accent5";
  383. break;
  384. case TableDesign.LightShadingAccent6:
  385. val.Value = "LightShading-Accent6";
  386. break;
  387. case TableDesign.LightList:
  388. val.Value = "LightList";
  389. break;
  390. case TableDesign.LightListAccent1:
  391. val.Value = "LightList-Accent1";
  392. break;
  393. case TableDesign.LightListAccent2:
  394. val.Value = "LightList-Accent2";
  395. break;
  396. case TableDesign.LightListAccent3:
  397. val.Value = "LightList-Accent3";
  398. break;
  399. case TableDesign.LightListAccent4:
  400. val.Value = "LightList-Accent4";
  401. break;
  402. case TableDesign.LightListAccent5:
  403. val.Value = "LightList-Accent5";
  404. break;
  405. case TableDesign.LightListAccent6:
  406. val.Value = "LightList-Accent6";
  407. break;
  408. case TableDesign.LightGrid:
  409. val.Value = "LightGrid";
  410. break;
  411. case TableDesign.LightGridAccent1:
  412. val.Value = "LightGrid-Accent1";
  413. break;
  414. case TableDesign.LightGridAccent2:
  415. val.Value = "LightGrid-Accent2";
  416. break;
  417. case TableDesign.LightGridAccent3:
  418. val.Value = "LightGrid-Accent3";
  419. break;
  420. case TableDesign.LightGridAccent4:
  421. val.Value = "LightGrid-Accent4";
  422. break;
  423. case TableDesign.LightGridAccent5:
  424. val.Value = "LightGrid-Accent5";
  425. break;
  426. case TableDesign.LightGridAccent6:
  427. val.Value = "LightGrid-Accent6";
  428. break;
  429. case TableDesign.MediumShading1:
  430. val.Value = "MediumShading1";
  431. break;
  432. case TableDesign.MediumShading1Accent1:
  433. val.Value = "MediumShading1-Accent1";
  434. break;
  435. case TableDesign.MediumShading1Accent2:
  436. val.Value = "MediumShading1-Accent2";
  437. break;
  438. case TableDesign.MediumShading1Accent3:
  439. val.Value = "MediumShading1-Accent3";
  440. break;
  441. case TableDesign.MediumShading1Accent4:
  442. val.Value = "MediumShading1-Accent4";
  443. break;
  444. case TableDesign.MediumShading1Accent5:
  445. val.Value = "MediumShading1-Accent5";
  446. break;
  447. case TableDesign.MediumShading1Accent6:
  448. val.Value = "MediumShading1-Accent6";
  449. break;
  450. case TableDesign.MediumShading2:
  451. val.Value = "MediumShading2";
  452. break;
  453. case TableDesign.MediumShading2Accent1:
  454. val.Value = "MediumShading2-Accent1";
  455. break;
  456. case TableDesign.MediumShading2Accent2:
  457. val.Value = "MediumShading2-Accent2";
  458. break;
  459. case TableDesign.MediumShading2Accent3:
  460. val.Value = "MediumShading2-Accent3";
  461. break;
  462. case TableDesign.MediumShading2Accent4:
  463. val.Value = "MediumShading2-Accent4";
  464. break;
  465. case TableDesign.MediumShading2Accent5:
  466. val.Value = "MediumShading2-Accent5";
  467. break;
  468. case TableDesign.MediumShading2Accent6:
  469. val.Value = "MediumShading2-Accent6";
  470. break;
  471. case TableDesign.MediumList1:
  472. val.Value = "MediumList1";
  473. break;
  474. case TableDesign.MediumList1Accent1:
  475. val.Value = "MediumList1-Accent1";
  476. break;
  477. case TableDesign.MediumList1Accent2:
  478. val.Value = "MediumList1-Accent2";
  479. break;
  480. case TableDesign.MediumList1Accent3:
  481. val.Value = "MediumList1-Accent3";
  482. break;
  483. case TableDesign.MediumList1Accent4:
  484. val.Value = "MediumList1-Accent4";
  485. break;
  486. case TableDesign.MediumList1Accent5:
  487. val.Value = "MediumList1-Accent5";
  488. break;
  489. case TableDesign.MediumList1Accent6:
  490. val.Value = "MediumList1-Accent6";
  491. break;
  492. case TableDesign.MediumList2:
  493. val.Value = "MediumList2";
  494. break;
  495. case TableDesign.MediumList2Accent1:
  496. val.Value = "MediumList2-Accent1";
  497. break;
  498. case TableDesign.MediumList2Accent2:
  499. val.Value = "MediumList2-Accent2";
  500. break;
  501. case TableDesign.MediumList2Accent3:
  502. val.Value = "MediumList2-Accent3";
  503. break;
  504. case TableDesign.MediumList2Accent4:
  505. val.Value = "MediumList2-Accent4";
  506. break;
  507. case TableDesign.MediumList2Accent5:
  508. val.Value = "MediumList2-Accent5";
  509. break;
  510. case TableDesign.MediumList2Accent6:
  511. val.Value = "MediumList2-Accent6";
  512. break;
  513. case TableDesign.MediumGrid1:
  514. val.Value = "MediumGrid1";
  515. break;
  516. case TableDesign.MediumGrid1Accent1:
  517. val.Value = "MediumGrid1-Accent1";
  518. break;
  519. case TableDesign.MediumGrid1Accent2:
  520. val.Value = "MediumGrid1-Accent2";
  521. break;
  522. case TableDesign.MediumGrid1Accent3:
  523. val.Value = "MediumGrid1-Accent3";
  524. break;
  525. case TableDesign.MediumGrid1Accent4:
  526. val.Value = "MediumGrid1-Accent4";
  527. break;
  528. case TableDesign.MediumGrid1Accent5:
  529. val.Value = "MediumGrid1-Accent5";
  530. break;
  531. case TableDesign.MediumGrid1Accent6:
  532. val.Value = "MediumGrid1-Accent6";
  533. break;
  534. case TableDesign.MediumGrid2:
  535. val.Value = "MediumGrid2";
  536. break;
  537. case TableDesign.MediumGrid2Accent1:
  538. val.Value = "MediumGrid2-Accent1";
  539. break;
  540. case TableDesign.MediumGrid2Accent2:
  541. val.Value = "MediumGrid2-Accent2";
  542. break;
  543. case TableDesign.MediumGrid2Accent3:
  544. val.Value = "MediumGrid2-Accent3";
  545. break;
  546. case TableDesign.MediumGrid2Accent4:
  547. val.Value = "MediumGrid2-Accent4";
  548. break;
  549. case TableDesign.MediumGrid2Accent5:
  550. val.Value = "MediumGrid2-Accent5";
  551. break;
  552. case TableDesign.MediumGrid2Accent6:
  553. val.Value = "MediumGrid2-Accent6";
  554. break;
  555. case TableDesign.MediumGrid3:
  556. val.Value = "MediumGrid3";
  557. break;
  558. case TableDesign.MediumGrid3Accent1:
  559. val.Value = "MediumGrid3-Accent1";
  560. break;
  561. case TableDesign.MediumGrid3Accent2:
  562. val.Value = "MediumGrid3-Accent2";
  563. break;
  564. case TableDesign.MediumGrid3Accent3:
  565. val.Value = "MediumGrid3-Accent3";
  566. break;
  567. case TableDesign.MediumGrid3Accent4:
  568. val.Value = "MediumGrid3-Accent4";
  569. break;
  570. case TableDesign.MediumGrid3Accent5:
  571. val.Value = "MediumGrid3-Accent5";
  572. break;
  573. case TableDesign.MediumGrid3Accent6:
  574. val.Value = "MediumGrid3-Accent6";
  575. break;
  576. case TableDesign.DarkList:
  577. val.Value = "DarkList";
  578. break;
  579. case TableDesign.DarkListAccent1:
  580. val.Value = "DarkList-Accent1";
  581. break;
  582. case TableDesign.DarkListAccent2:
  583. val.Value = "DarkList-Accent2";
  584. break;
  585. case TableDesign.DarkListAccent3:
  586. val.Value = "DarkList-Accent3";
  587. break;
  588. case TableDesign.DarkListAccent4:
  589. val.Value = "DarkList-Accent4";
  590. break;
  591. case TableDesign.DarkListAccent5:
  592. val.Value = "DarkList-Accent5";
  593. break;
  594. case TableDesign.DarkListAccent6:
  595. val.Value = "DarkList-Accent6";
  596. break;
  597. case TableDesign.ColorfulShading:
  598. val.Value = "ColorfulShading";
  599. break;
  600. case TableDesign.ColorfulShadingAccent1:
  601. val.Value = "ColorfulShading-Accent1";
  602. break;
  603. case TableDesign.ColorfulShadingAccent2:
  604. val.Value = "ColorfulShading-Accent2";
  605. break;
  606. case TableDesign.ColorfulShadingAccent3:
  607. val.Value = "ColorfulShading-Accent3";
  608. break;
  609. case TableDesign.ColorfulShadingAccent4:
  610. val.Value = "ColorfulShading-Accent4";
  611. break;
  612. case TableDesign.ColorfulShadingAccent5:
  613. val.Value = "ColorfulShading-Accent5";
  614. break;
  615. case TableDesign.ColorfulShadingAccent6:
  616. val.Value = "ColorfulShading-Accent6";
  617. break;
  618. case TableDesign.ColorfulList:
  619. val.Value = "ColorfulList";
  620. break;
  621. case TableDesign.ColorfulListAccent1:
  622. val.Value = "ColorfulList-Accent1";
  623. break;
  624. case TableDesign.ColorfulListAccent2:
  625. val.Value = "ColorfulList-Accent2";
  626. break;
  627. case TableDesign.ColorfulListAccent3:
  628. val.Value = "ColorfulList-Accent3";
  629. break;
  630. case TableDesign.ColorfulListAccent4:
  631. val.Value = "ColorfulList-Accent4";
  632. break;
  633. case TableDesign.ColorfulListAccent5:
  634. val.Value = "ColorfulList-Accent5";
  635. break;
  636. case TableDesign.ColorfulListAccent6:
  637. val.Value = "ColorfulList-Accent6";
  638. break;
  639. case TableDesign.ColorfulGrid:
  640. val.Value = "ColorfulGrid";
  641. break;
  642. case TableDesign.ColorfulGridAccent1:
  643. val.Value = "ColorfulGrid-Accent1";
  644. break;
  645. case TableDesign.ColorfulGridAccent2:
  646. val.Value = "ColorfulGrid-Accent2";
  647. break;
  648. case TableDesign.ColorfulGridAccent3:
  649. val.Value = "ColorfulGrid-Accent3";
  650. break;
  651. case TableDesign.ColorfulGridAccent4:
  652. val.Value = "ColorfulGrid-Accent4";
  653. break;
  654. case TableDesign.ColorfulGridAccent5:
  655. val.Value = "ColorfulGrid-Accent5";
  656. break;
  657. case TableDesign.ColorfulGridAccent6:
  658. val.Value = "ColorfulGrid-Accent6";
  659. break;
  660. default:
  661. break;
  662. }
  663. }
  664. if( Document._styles == null )
  665. {
  666. PackagePart word_styles = Document._package.GetPart( new Uri( "/word/styles.xml", UriKind.Relative ) );
  667. using( TextReader tr = new StreamReader( word_styles.GetStream() ) )
  668. Document._styles = XDocument.Load( tr );
  669. }
  670. var tableStyle =
  671. (
  672. from e in Document._styles.Descendants()
  673. let styleId = e.Attribute( XName.Get( "styleId", DocX.w.NamespaceName ) )
  674. where ( styleId != null && styleId.Value == val.Value )
  675. select e
  676. ).FirstOrDefault();
  677. if( tableStyle == null )
  678. {
  679. XDocument external_style_doc = HelperFunctions.DecompressXMLResource( "Xceed.Words.NET.Resources.styles.xml.gz" );
  680. var styleElement =
  681. (
  682. from e in external_style_doc.Descendants()
  683. let styleId = e.Attribute( XName.Get( "styleId", DocX.w.NamespaceName ) )
  684. where ( styleId != null && styleId.Value == val.Value )
  685. select e
  686. ).First();
  687. Document._styles.Element( XName.Get( "styles", DocX.w.NamespaceName ) ).Add( styleElement );
  688. }
  689. }
  690. }
  691. /// <summary>
  692. /// Returns the index of this Table.
  693. /// </summary>
  694. /// <example>
  695. /// Replace the first table in this document with a new Table.
  696. /// <code>
  697. /// // Load a document into memory.
  698. /// using (DocX document = DocX.Load(@"Test.docx"))
  699. /// {
  700. /// // Get the first Table in this document.
  701. /// Table t = document.Tables[0];
  702. ///
  703. /// // Get the character index of Table t in this document.
  704. /// int index = t.Index;
  705. ///
  706. /// // Remove Table t.
  707. /// t.Remove();
  708. ///
  709. /// // Insert a new Table at the original index of Table t.
  710. /// Table newTable = document.InsertTable(index, 4, 4);
  711. ///
  712. /// // Set the design of this new Table, so that we can see it.
  713. /// newTable.Design = TableDesign.LightShadingAccent1;
  714. ///
  715. /// // Save all changes made to the document.
  716. /// document.Save();
  717. /// } // Release this document from memory.
  718. /// </code>
  719. /// </example>
  720. public int Index
  721. {
  722. get
  723. {
  724. int index = 0;
  725. IEnumerable<XElement> previous = Xml.ElementsBeforeSelf();
  726. foreach( XElement e in previous )
  727. index += Paragraph.GetElementTextLength( e );
  728. return index;
  729. }
  730. }
  731. /// <summary>
  732. /// The custom design/style to apply to this table.
  733. /// </summary>
  734. public string CustomTableDesignName
  735. {
  736. get
  737. {
  738. return _customTableDesignName;
  739. }
  740. set
  741. {
  742. _customTableDesignName = value;
  743. this.Design = TableDesign.Custom;
  744. }
  745. }
  746. /// <summary>
  747. /// Gets or sets the value of the Table Caption (Alternate Text Title) of this table.
  748. /// </summary>
  749. public string TableCaption
  750. {
  751. get
  752. {
  753. var tblPr = Xml.Element( XName.Get( "tblPr", DocX.w.NamespaceName ) );
  754. var caption = tblPr?.Element( XName.Get( "tblCaption", DocX.w.NamespaceName ) );
  755. if( caption != null )
  756. return caption.GetAttribute( XName.Get( "val", DocX.w.NamespaceName ) );
  757. return null;
  758. }
  759. set
  760. {
  761. var tblPr = Xml.Element( XName.Get( "tblPr", DocX.w.NamespaceName ) );
  762. if( tblPr != null )
  763. {
  764. var caption = tblPr.Descendants( XName.Get( "tblCaption", DocX.w.NamespaceName ) ).FirstOrDefault();
  765. if( caption != null )
  766. {
  767. caption.Remove();
  768. }
  769. caption = new XElement( XName.Get( "tblCaption", DocX.w.NamespaceName ), new XAttribute( XName.Get( "val", DocX.w.NamespaceName ), value ) );
  770. tblPr.Add( caption );
  771. }
  772. }
  773. }
  774. /// <summary>
  775. /// Gets or sets the value of the Table Description (Alternate Text Description) of this table.
  776. /// </summary>
  777. public string TableDescription
  778. {
  779. get
  780. {
  781. var tblPr = Xml.Element( XName.Get( "tblPr", DocX.w.NamespaceName ) );
  782. var description = tblPr?.Element( XName.Get( "tblDescription", DocX.w.NamespaceName ) );
  783. if( description != null )
  784. return description.GetAttribute( XName.Get( "val", DocX.w.NamespaceName ) );
  785. return null;
  786. }
  787. set
  788. {
  789. var tblPr = Xml.Element( XName.Get( "tblPr", DocX.w.NamespaceName ) );
  790. if( tblPr != null )
  791. {
  792. var description = tblPr.Descendants( XName.Get( "tblDescription", DocX.w.NamespaceName ) ).FirstOrDefault();
  793. description?.Remove();
  794. description = new XElement( XName.Get( "tblDescription", DocX.w.NamespaceName ), new XAttribute( XName.Get( "val", DocX.w.NamespaceName ), value ) );
  795. tblPr.Add( description );
  796. }
  797. }
  798. }
  799. public TableLook TableLook
  800. {
  801. get;
  802. set;
  803. }
  804. #endregion
  805. #region Constructors
  806. internal Table( DocX document, XElement xml )
  807. : base( document, xml )
  808. {
  809. _autofit = AutoFit.ColumnWidth;
  810. this.Xml = xml;
  811. this.PackagePart = document.PackagePart;
  812. var properties = xml.Element( XName.Get( "tblPr", DocX.w.NamespaceName ) );
  813. var alignment = properties.Element( XName.Get( "jc", DocX.w.NamespaceName ) );
  814. if( alignment != null )
  815. {
  816. var val = alignment.Attribute( XName.Get( "val", DocX.w.NamespaceName ) );
  817. if( val != null )
  818. {
  819. _alignment = (Alignment)Enum.Parse( typeof( Alignment ), val.Value );
  820. }
  821. }
  822. var style = properties?.Element( XName.Get( "tblStyle", DocX.w.NamespaceName ) );
  823. if( style != null )
  824. {
  825. var val = style.Attribute( XName.Get( "val", DocX.w.NamespaceName ) );
  826. if( val != null )
  827. {
  828. String cleanValue = val.Value.Replace( "-", string.Empty );
  829. if( Enum.IsDefined( typeof( TableDesign ), cleanValue ) )
  830. {
  831. _design = ( TableDesign )Enum.Parse( typeof( TableDesign ), cleanValue );
  832. }
  833. else
  834. {
  835. _design = TableDesign.Custom;
  836. }
  837. }
  838. else
  839. {
  840. _design = TableDesign.None;
  841. }
  842. }
  843. else
  844. {
  845. _design = TableDesign.None;
  846. }
  847. var tableLook = properties?.Element( XName.Get( "tblLook", DocX.w.NamespaceName ) );
  848. if( tableLook != null )
  849. {
  850. this.TableLook = new TableLook( tableLook.GetAttribute( XName.Get( "firstRow", DocX.w.NamespaceName ) ) == "1",
  851. tableLook.GetAttribute( XName.Get( "lastRow", DocX.w.NamespaceName ) ) == "1",
  852. tableLook.GetAttribute( XName.Get( "firstColumn", DocX.w.NamespaceName ) ) == "1",
  853. tableLook.GetAttribute( XName.Get( "lastColumn", DocX.w.NamespaceName ) ) == "1",
  854. tableLook.GetAttribute( XName.Get( "noHBand", DocX.w.NamespaceName ) ) == "1",
  855. tableLook.GetAttribute( XName.Get( "noVBand", DocX.w.NamespaceName ) ) == "1" );
  856. }
  857. }
  858. #endregion
  859. #region Public Methods
  860. /// <summary>
  861. /// Merge cells in given column starting with startRow and ending with endRow.
  862. /// </summary>
  863. public void MergeCellsInColumn( int columnIndex, int startRow, int endRow )
  864. {
  865. // Check for valid start and end indexes.
  866. if( columnIndex < 0 || columnIndex >= ColumnCount )
  867. throw new IndexOutOfRangeException();
  868. if( startRow < 0 || endRow <= startRow || endRow >= Rows.Count )
  869. throw new IndexOutOfRangeException();
  870. // Foreach each Cell between startIndex and endIndex inclusive.
  871. foreach( Row row in Rows.Where( ( z, i ) => i > startRow && i <= endRow ) )
  872. {
  873. var c = row.Cells[ columnIndex ];
  874. var tcPr = c.Xml.Element( XName.Get( "tcPr", DocX.w.NamespaceName ) );
  875. if( tcPr == null )
  876. {
  877. c.Xml.SetElementValue( XName.Get( "tcPr", DocX.w.NamespaceName ), string.Empty );
  878. tcPr = c.Xml.Element( XName.Get( "tcPr", DocX.w.NamespaceName ) );
  879. }
  880. var vMerge = tcPr.Element( XName.Get( "vMerge", DocX.w.NamespaceName ) );
  881. if( vMerge == null )
  882. {
  883. tcPr.SetElementValue( XName.Get( "vMerge", DocX.w.NamespaceName ), string.Empty );
  884. vMerge = tcPr.Element( XName.Get( "vMerge", DocX.w.NamespaceName ) );
  885. }
  886. }
  887. /*
  888. * Get the tcPr (table cell properties) element for the first cell in this merge,
  889. * null will be returned if no such element exists.
  890. */
  891. var startRowCellsCount = this.Rows[ startRow ].Cells.Count;
  892. var start_tcPr = ( columnIndex > startRowCellsCount )
  893. ? this.Rows[ startRow ].Cells[ startRowCellsCount - 1 ].Xml.Element( XName.Get( "tcPr", DocX.w.NamespaceName ) )
  894. : this.Rows[ startRow ].Cells[ columnIndex ].Xml.Element( XName.Get( "tcPr", DocX.w.NamespaceName ) );
  895. if( start_tcPr == null )
  896. {
  897. this.Rows[ startRow ].Cells[ columnIndex ].Xml.SetElementValue( XName.Get( "tcPr", DocX.w.NamespaceName ), string.Empty );
  898. start_tcPr = this.Rows[ startRow ].Cells[ columnIndex ].Xml.Element( XName.Get( "tcPr", DocX.w.NamespaceName ) );
  899. }
  900. /*
  901. * Get the gridSpan element of this row,
  902. * null will be returned if no such element exists.
  903. */
  904. var start_vMerge = start_tcPr.Element( XName.Get( "vMerge", DocX.w.NamespaceName ) );
  905. if( start_vMerge == null )
  906. {
  907. start_tcPr.SetElementValue( XName.Get( "vMerge", DocX.w.NamespaceName ), string.Empty );
  908. start_vMerge = start_tcPr.Element( XName.Get( "vMerge", DocX.w.NamespaceName ) );
  909. }
  910. start_vMerge.SetAttributeValue( XName.Get( "val", DocX.w.NamespaceName ), "restart" );
  911. }
  912. /// <summary>
  913. /// Set the direction of all content in this Table.
  914. /// </summary>
  915. /// <param name="direction">(Left to Right) or (Right to Left)</param>
  916. /// <example>
  917. /// Set the content direction for all content in a table to RightToLeft.
  918. /// <code>
  919. /// // Load a document.
  920. /// using (DocX document = DocX.Load(@"Test.docx"))
  921. /// {
  922. /// // Get the first table in a document.
  923. /// Table table = document.Tables[0];
  924. ///
  925. /// // Set the content direction for all content in this table to RightToLeft.
  926. /// table.SetDirection(Direction.RightToLeft);
  927. ///
  928. /// // Save all changes made to this document.
  929. /// document.Save();
  930. /// }
  931. /// </code>
  932. /// </example>
  933. public void SetDirection( Direction direction )
  934. {
  935. var tblPr = GetOrCreate_tblPr();
  936. tblPr.Add( new XElement( DocX.w + "bidiVisual" ) );
  937. foreach( Row r in Rows )
  938. {
  939. r.SetDirection( direction );
  940. }
  941. }
  942. /// <summary>
  943. /// Remove this Table from this document.
  944. /// </summary>
  945. /// <example>
  946. /// Remove the first Table from this document.
  947. /// <code>
  948. /// // Load a document into memory.
  949. /// using (DocX document = DocX.Load(@"Test.docx"))
  950. /// {
  951. /// // Get the first Table in this document.
  952. /// Table t = d.Tables[0];
  953. ///
  954. /// // Remove this Table.
  955. /// t.Remove();
  956. ///
  957. /// // Save all changes made to the document.
  958. /// document.Save();
  959. /// } // Release this document from memory.
  960. /// </code>
  961. /// </example>
  962. public void Remove()
  963. {
  964. this.Xml.Remove();
  965. }
  966. /// <summary>
  967. /// Insert a row at the end of this table.
  968. /// </summary>
  969. /// <example>
  970. /// <code>
  971. /// // Load a document.
  972. /// using (DocX document = DocX.Load(@"C:\Example\Test.docx"))
  973. /// {
  974. /// // Get the first table in this document.
  975. /// Table table = document.Tables[0];
  976. ///
  977. /// // Insert a new row at the end of this table.
  978. /// Row row = table.InsertRow();
  979. ///
  980. /// // Loop through each cell in this new row.
  981. /// foreach (Cell c in row.Cells)
  982. /// {
  983. /// // Set the text of each new cell to "Hello".
  984. /// c.Paragraphs[0].InsertText("Hello", false);
  985. /// }
  986. ///
  987. /// // Save the document to a new file.
  988. /// document.SaveAs(@"C:\Example\Test2.docx");
  989. /// }// Release this document from memory.
  990. /// </code>
  991. /// </example>
  992. /// <returns>A new row.</returns>
  993. public Row InsertRow()
  994. {
  995. return this.InsertRow( this.RowCount );
  996. }
  997. /// <summary>
  998. /// Insert a copy of a row at the end of this table.
  999. /// </summary>
  1000. /// <returns>A new row.</returns>
  1001. public Row InsertRow( Row row )
  1002. {
  1003. return this.InsertRow( row, this.RowCount );
  1004. }
  1005. /// <summary>
  1006. /// Insert a column to the right of a Table.
  1007. /// </summary>
  1008. /// <example>
  1009. /// <code>
  1010. /// // Load a document.
  1011. /// using (DocX document = DocX.Load(@"C:\Example\Test.docx"))
  1012. /// {
  1013. /// // Get the first Table in this document.
  1014. /// Table table = document.Tables[0];
  1015. ///
  1016. /// // Insert a new column to this right of this table.
  1017. /// table.InsertColumn();
  1018. ///
  1019. /// // Set the new columns text to "Row no."
  1020. /// table.Rows[0].Cells[table.ColumnCount - 1].Paragraph.InsertText("Row no.", false);
  1021. ///
  1022. /// // Loop through each row in the table.
  1023. /// for (int i = 1; i &lt; table.Rows.Count; i++)
  1024. /// {
  1025. /// // The current row.
  1026. /// Row row = table.Rows[i];
  1027. ///
  1028. /// // The cell in this row that belongs to the new column.
  1029. /// Cell cell = row.Cells[table.ColumnCount - 1];
  1030. ///
  1031. /// // The first Paragraph that this cell houses.
  1032. /// Paragraph p = cell.Paragraphs[0];
  1033. ///
  1034. /// // Insert this rows index.
  1035. /// p.InsertText(i.ToString(), false);
  1036. /// }
  1037. ///
  1038. /// document.Save();
  1039. /// }// Release this document from memory.
  1040. /// </code>
  1041. /// </example>
  1042. public void InsertColumn()
  1043. {
  1044. this.InsertColumn( this.ColumnCount, true );
  1045. }
  1046. /// <summary>
  1047. /// Remove the last row from this Table.
  1048. /// </summary>
  1049. /// <example>
  1050. /// Remove the last row from a Table.
  1051. /// <code>
  1052. /// // Load a document.
  1053. /// using (DocX document = DocX.Load(@"C:\Example\Test.docx"))
  1054. /// {
  1055. /// // Get the first table in this document.
  1056. /// Table table = document.Tables[0];
  1057. ///
  1058. /// // Remove the last row from this table.
  1059. /// table.RemoveRow();
  1060. ///
  1061. /// // Save the document.
  1062. /// document.Save();
  1063. /// }// Release this document from memory.
  1064. /// </code>
  1065. /// </example>
  1066. public void RemoveRow()
  1067. {
  1068. this.RemoveRow( RowCount - 1 );
  1069. }
  1070. /// <summary>
  1071. /// Remove a row from this Table.
  1072. /// </summary>
  1073. /// <param name="index">The row to remove.</param>
  1074. /// <example>
  1075. /// Remove the first row from a Table.
  1076. /// <code>
  1077. /// // Load a document.
  1078. /// using (DocX document = DocX.Load(@"C:\Example\Test.docx"))
  1079. /// {
  1080. /// // Get the first table in this document.
  1081. /// Table table = document.Tables[0];
  1082. ///
  1083. /// // Remove the first row from this table.
  1084. /// table.RemoveRow(0);
  1085. ///
  1086. /// // Save the document.
  1087. /// document.Save();
  1088. /// }// Release this document from memory.
  1089. /// </code>
  1090. /// </example>
  1091. public void RemoveRow( int index )
  1092. {
  1093. if( index < 0 || index > RowCount - 1 )
  1094. throw new IndexOutOfRangeException();
  1095. this.Rows[ index ].Xml.Remove();
  1096. if( this.Rows.Count == 0 )
  1097. {
  1098. this.Remove();
  1099. }
  1100. }
  1101. /// <summary>
  1102. /// Remove the last column for this Table.
  1103. /// </summary>
  1104. /// <example>
  1105. /// Remove the last column from a Table.
  1106. /// <code>
  1107. /// // Load a document.
  1108. /// using (DocX document = DocX.Load(@"C:\Example\Test.docx"))
  1109. /// {
  1110. /// // Get the first table in this document.
  1111. /// Table table = document.Tables[0];
  1112. ///
  1113. /// // Remove the last column from this table.
  1114. /// table.RemoveColumn();
  1115. ///
  1116. /// // Save the document.
  1117. /// document.Save();
  1118. /// }// Release this document from memory.
  1119. /// </code>
  1120. /// </example>
  1121. public void RemoveColumn()
  1122. {
  1123. this.RemoveColumn( this.ColumnCount - 1 );
  1124. }
  1125. /// <summary>
  1126. /// Remove a column from this Table.
  1127. /// </summary>
  1128. /// <param name="index">The column to remove.</param>
  1129. /// <example>
  1130. /// Remove the first column from a Table.
  1131. /// <code>
  1132. /// // Load a document.
  1133. /// using (DocX document = DocX.Load(@"C:\Example\Test.docx"))
  1134. /// {
  1135. /// // Get the first table in this document.
  1136. /// Table table = document.Tables[0];
  1137. ///
  1138. /// // Remove the first column from this table.
  1139. /// table.RemoveColumn(0);
  1140. ///
  1141. /// // Save the document.
  1142. /// document.Save();
  1143. /// }// Release this document from memory.
  1144. /// </code>
  1145. /// </example>
  1146. public void RemoveColumn( int index )
  1147. {
  1148. if( ( index < 0 ) || ( index > this.ColumnCount - 1 ) )
  1149. throw new IndexOutOfRangeException();
  1150. foreach( Row r in Rows )
  1151. {
  1152. if( r.Cells.Count < this.ColumnCount )
  1153. {
  1154. int gridAfterValue = r.GridAfter;
  1155. int posIndex = 0;
  1156. int currentPos = 0;
  1157. for( int i = 0; i < r.Cells.Count; ++i )
  1158. {
  1159. var rowCell = r.Cells[ i ];
  1160. int gridSpanValue = ( rowCell.GridSpan != 0 ) ? rowCell.GridSpan - 1 : 0;
  1161. // checks to see if index is between the lowest and highest cell value.
  1162. if( ( ( index - gridAfterValue ) >= currentPos )
  1163. && ( ( index - gridAfterValue ) <= ( currentPos + gridSpanValue ) ) )
  1164. {
  1165. r.Cells[ posIndex ].Xml.Remove();
  1166. break;
  1167. }
  1168. ++posIndex;
  1169. currentPos += ( gridSpanValue + 1 );
  1170. }
  1171. }
  1172. else
  1173. {
  1174. r.Cells[ index ].Xml.Remove();
  1175. }
  1176. }
  1177. _cachedColumnCount = -1;
  1178. }
  1179. /// <summary>
  1180. /// Insert a row into this table.
  1181. /// </summary>
  1182. /// <example>
  1183. /// <code>
  1184. /// // Load a document.
  1185. /// using (DocX document = DocX.Load(@"C:\Example\Test.docx"))
  1186. /// {
  1187. /// // Get the first table in this document.
  1188. /// Table table = document.Tables[0];
  1189. ///
  1190. /// // Insert a new row at index 1 in this table.
  1191. /// Row row = table.InsertRow(1);
  1192. ///
  1193. /// // Loop through each cell in this new row.
  1194. /// foreach (Cell c in row.Cells)
  1195. /// {
  1196. /// // Set the text of each new cell to "Hello".
  1197. /// c.Paragraphs[0].InsertText("Hello", false);
  1198. /// }
  1199. ///
  1200. /// // Save the document to a new file.
  1201. /// document.SaveAs(@"C:\Example\Test2.docx");
  1202. /// }// Release this document from memory.
  1203. /// </code>
  1204. /// </example>
  1205. /// <param name="index">Index to insert row at.</param>
  1206. /// <returns>A new Row</returns>
  1207. public Row InsertRow( int index )
  1208. {
  1209. if( ( index < 0 ) || ( index > this.RowCount ) )
  1210. throw new IndexOutOfRangeException();
  1211. var content = new List<XElement>();
  1212. for( int i = 0; i < ColumnCount; i++ )
  1213. {
  1214. var cell = ( ( _columnWidths != null ) && ( _columnWidths.Length > i ) )
  1215. ? HelperFunctions.CreateTableCell( _columnWidths[ i ] * 20 )
  1216. : HelperFunctions.CreateTableCell();
  1217. content.Add( cell );
  1218. }
  1219. return this.InsertRow( content, index );
  1220. }
  1221. /// <summary>
  1222. /// Insert a copy of a row into this table.
  1223. /// </summary>
  1224. /// <param name="row">Row to copy and insert.</param>
  1225. /// <param name="index">Index to insert row at.</param>
  1226. /// <returns>A new Row</returns>
  1227. public Row InsertRow( Row row, int index )
  1228. {
  1229. if( row == null )
  1230. throw new ArgumentNullException( "row" );
  1231. if( index < 0 || index > RowCount )
  1232. throw new IndexOutOfRangeException();
  1233. var content = row.Xml.Elements( XName.Get( "tc", DocX.w.NamespaceName ) ).Select( element => HelperFunctions.CloneElement( element ) ).ToList();
  1234. return this.InsertRow( content, index );
  1235. }
  1236. /// <summary>
  1237. /// Insert a column into a table.
  1238. /// </summary>
  1239. /// <param name="index">The index to insert the column at.</param>
  1240. /// <param name="direction">The side in which you wish to place the colum : True for right, false for left.</param>
  1241. /// <example>
  1242. /// Insert a column to the left of a table.
  1243. /// <code>
  1244. /// // Load a document.
  1245. /// using (DocX document = DocX.Load(@"C:\Example\Test.docx"))
  1246. /// {
  1247. /// // Get the first Table in this document.
  1248. /// Table table = document.Tables[0];
  1249. ///
  1250. /// // Insert a new column to this left of this table.
  1251. /// table.InsertColumn(0, false);
  1252. ///
  1253. /// // Set the new columns text to "Row no."
  1254. /// table.Rows[0].Cells[table.ColumnCount - 1].Paragraph.InsertText("Row no.", false);
  1255. ///
  1256. /// // Loop through each row in the table.
  1257. /// for (int i = 1; i &lt; table.Rows.Count; i++)
  1258. /// {
  1259. /// // The current row.
  1260. /// Row row = table.Rows[i];
  1261. ///
  1262. /// // The cell in this row that belongs to the new column.
  1263. /// Cell cell = row.Cells[table.ColumnCount - 1];
  1264. ///
  1265. /// // The first Paragraph that this cell houses.
  1266. /// Paragraph p = cell.Paragraphs[0];
  1267. ///
  1268. /// // Insert this rows index.
  1269. /// p.InsertText(i.ToString(), false);
  1270. /// }
  1271. ///
  1272. /// document.Save();
  1273. /// }// Release this document from memory.
  1274. /// </code>
  1275. /// </example>
  1276. public void InsertColumn( int index, bool direction )
  1277. {
  1278. var colCount = this.ColumnCount;
  1279. if( (index <= 0) && (index > colCount ) )
  1280. throw new NullReferenceException( "index should be greater than 0 and smaller or equals to this.ColumnCount." );
  1281. if( this.RowCount > 0 )
  1282. {
  1283. _cachedColumnCount = -1;
  1284. foreach( Row r in this.Rows )
  1285. {
  1286. // create cell
  1287. var cell = HelperFunctions.CreateTableCell();
  1288. // insert cell
  1289. if( r.Cells.Count < colCount )
  1290. {
  1291. if( index >= colCount )
  1292. {
  1293. this.AddCellToRow( r, cell, r.Cells.Count - 1, direction );
  1294. }
  1295. else
  1296. {
  1297. int gridAfterValue = r.GridAfter;
  1298. int currentPosition = 1;
  1299. int posIndex = 1;
  1300. foreach( var rowCell in r.Cells )
  1301. {
  1302. int gridSpanValue = ( rowCell.GridSpan != 0 ) ? rowCell.GridSpan - 1 : 0;
  1303. var tcPr = rowCell.Xml.Element( XName.Get( "tcPr", DocX.w.NamespaceName ) );
  1304. // Check if the cell have a gridSpan and if the index is between the lowest and highest cell value
  1305. if( ( ( index - gridAfterValue ) >= currentPosition )
  1306. && ( ( index - gridAfterValue ) <= ( currentPosition + gridSpanValue ) ) )
  1307. {
  1308. var dir = ( direction && ( index == ( currentPosition + gridSpanValue ) ) );
  1309. this.AddCellToRow( r, cell, posIndex - 1, dir );
  1310. break;
  1311. }
  1312. ++posIndex;
  1313. currentPosition += (gridSpanValue + 1);
  1314. }
  1315. }
  1316. }
  1317. else
  1318. {
  1319. this.AddCellToRow( r, cell, index - 1, direction );
  1320. }
  1321. }
  1322. }
  1323. }
  1324. /// <summary>
  1325. /// Insert a page break before a Table.
  1326. /// </summary>
  1327. /// <example>
  1328. /// Insert a Table and a Paragraph into a document with a page break between them.
  1329. /// <code>
  1330. /// // Create a new document.
  1331. /// using (DocX document = DocX.Create(@"Test.docx"))
  1332. /// {
  1333. /// // Insert a new Paragraph.
  1334. /// Paragraph p1 = document.InsertParagraph("Paragraph", false);
  1335. ///
  1336. /// // Insert a new Table.
  1337. /// Table t1 = document.InsertTable(2, 2);
  1338. /// t1.Design = TableDesign.LightShadingAccent1;
  1339. ///
  1340. /// // Insert a page break before this Table.
  1341. /// t1.InsertPageBreakBeforeSelf();
  1342. ///
  1343. /// // Save this document.
  1344. /// document.Save();
  1345. /// }// Release this document from memory.
  1346. /// </code>
  1347. /// </example>
  1348. public override void InsertPageBreakBeforeSelf()
  1349. {
  1350. base.InsertPageBreakBeforeSelf();
  1351. }
  1352. public void SetWidths( float[] widths )
  1353. {
  1354. _columnWidths = widths;
  1355. for( int i = 0; i < this.Rows.Count; ++i )
  1356. {
  1357. var row = this.Rows[ i ];
  1358. for( int j = 0; j < widths.Length; ++j )
  1359. {
  1360. if( row.Cells.Count > j )
  1361. {
  1362. row.Cells[ j ].Width = widths[ j ];
  1363. }
  1364. }
  1365. }
  1366. }
  1367. public void SetWidthsPercentage( float[] widthsPercentage, float? totalWidth )
  1368. {
  1369. if( totalWidth == null )
  1370. totalWidth = this.Document.PageWidth - this.Document.MarginLeft - this.Document.MarginRight;
  1371. List<float> widths = new List<float>( widthsPercentage.Length );
  1372. widthsPercentage.ToList().ForEach( pWidth => { widths.Add( ( pWidth * totalWidth.Value / 100 ) * ( 96 / 72 ) ); } );
  1373. SetWidths( widths.ToArray() );
  1374. }
  1375. /// <summary>
  1376. /// Insert a page break after a Table.
  1377. /// </summary>
  1378. /// <example>
  1379. /// Insert a Table and a Paragraph into a document with a page break between them.
  1380. /// <code>
  1381. /// // Create a new document.
  1382. /// using (DocX document = DocX.Create(@"Test.docx"))
  1383. /// {
  1384. /// // Insert a new Table.
  1385. /// Table t1 = document.InsertTable(2, 2);
  1386. /// t1.Design = TableDesign.LightShadingAccent1;
  1387. ///
  1388. /// // Insert a page break after this Table.
  1389. /// t1.InsertPageBreakAfterSelf();
  1390. ///
  1391. /// // Insert a new Paragraph.
  1392. /// Paragraph p1 = document.InsertParagraph("Paragraph", false);
  1393. ///
  1394. /// // Save this document.
  1395. /// document.Save();
  1396. /// }// Release this document from memory.
  1397. /// </code>
  1398. /// </example>
  1399. public override void InsertPageBreakAfterSelf()
  1400. {
  1401. base.InsertPageBreakAfterSelf();
  1402. }
  1403. /// <summary>
  1404. /// Insert a new Table before this Table, this Table can be from this document or another document.
  1405. /// </summary>
  1406. /// <param name="t">The Table t to be inserted</param>
  1407. /// <returns>A new Table inserted before this Table.</returns>
  1408. /// <example>
  1409. /// Insert a new Table before this Table.
  1410. /// <code>
  1411. /// // Place holder for a Table.
  1412. /// Table t;
  1413. ///
  1414. /// // Load document a.
  1415. /// using (DocX documentA = DocX.Load(@"a.docx"))
  1416. /// {
  1417. /// // Get the first Table from this document.
  1418. /// t = documentA.Tables[0];
  1419. /// }
  1420. ///
  1421. /// // Load document b.
  1422. /// using (DocX documentB = DocX.Load(@"b.docx"))
  1423. /// {
  1424. /// // Get the first Table in document b.
  1425. /// Table t2 = documentB.Tables[0];
  1426. ///
  1427. /// // Insert the Table from document a before this Table.
  1428. /// Table newTable = t2.InsertTableBeforeSelf(t);
  1429. ///
  1430. /// // Save all changes made to document b.
  1431. /// documentB.Save();
  1432. /// }// Release this document from memory.
  1433. /// </code>
  1434. /// </example>
  1435. public override Table InsertTableBeforeSelf( Table t )
  1436. {
  1437. return base.InsertTableBeforeSelf( t );
  1438. }
  1439. /// <summary>
  1440. /// Insert a new Table into this document before this Table.
  1441. /// </summary>
  1442. /// <param name="rowCount">The number of rows this Table should have.</param>
  1443. /// <param name="columnCount">The number of columns this Table should have.</param>
  1444. /// <returns>A new Table inserted before this Table.</returns>
  1445. /// <example>
  1446. /// <code>
  1447. /// // Create a new document.
  1448. /// using (DocX document = DocX.Create(@"Test.docx"))
  1449. /// {
  1450. /// //Insert a Table into this document.
  1451. /// Table t = document.InsertTable(2, 2);
  1452. /// t.Design = TableDesign.LightShadingAccent1;
  1453. /// t.Alignment = Alignment.center;
  1454. ///
  1455. /// // Insert a new Table before this Table.
  1456. /// Table newTable = t.InsertTableBeforeSelf(2, 2);
  1457. /// newTable.Design = TableDesign.LightShadingAccent2;
  1458. /// newTable.Alignment = Alignment.center;
  1459. ///
  1460. /// // Save all changes made to this document.
  1461. /// document.Save();
  1462. /// }// Release this document from memory.
  1463. /// </code>
  1464. /// </example>
  1465. public override Table InsertTableBeforeSelf( int rowCount, int columnCount )
  1466. {
  1467. return base.InsertTableBeforeSelf( rowCount, columnCount );
  1468. }
  1469. /// <summary>
  1470. /// Insert a new Table after this Table, this Table can be from this document or another document.
  1471. /// </summary>
  1472. /// <param name="t">The Table t to be inserted</param>
  1473. /// <returns>A new Table inserted after this Table.</returns>
  1474. /// <example>
  1475. /// Insert a new Table after this Table.
  1476. /// <code>
  1477. /// // Place holder for a Table.
  1478. /// Table t;
  1479. ///
  1480. /// // Load document a.
  1481. /// using (DocX documentA = DocX.Load(@"a.docx"))
  1482. /// {
  1483. /// // Get the first Table from this document.
  1484. /// t = documentA.Tables[0];
  1485. /// }
  1486. ///
  1487. /// // Load document b.
  1488. /// using (DocX documentB = DocX.Load(@"b.docx"))
  1489. /// {
  1490. /// // Get the first Table in document b.
  1491. /// Table t2 = documentB.Tables[0];
  1492. ///
  1493. /// // Insert the Table from document a after this Table.
  1494. /// Table newTable = t2.InsertTableAfterSelf(t);
  1495. ///
  1496. /// // Save all changes made to document b.
  1497. /// documentB.Save();
  1498. /// }// Release this document from memory.
  1499. /// </code>
  1500. /// </example>
  1501. public override Table InsertTableAfterSelf( Table t )
  1502. {
  1503. return base.InsertTableAfterSelf( t );
  1504. }
  1505. /// <summary>
  1506. /// Insert a new Table into this document after this Table.
  1507. /// </summary>
  1508. /// <param name="rowCount">The number of rows this Table should have.</param>
  1509. /// <param name="columnCount">The number of columns this Table should have.</param>
  1510. /// <returns>A new Table inserted before this Table.</returns>
  1511. /// <example>
  1512. /// <code>
  1513. /// // Create a new document.
  1514. /// using (DocX document = DocX.Create(@"Test.docx"))
  1515. /// {
  1516. /// //Insert a Table into this document.
  1517. /// Table t = document.InsertTable(2, 2);
  1518. /// t.Design = TableDesign.LightShadingAccent1;
  1519. /// t.Alignment = Alignment.center;
  1520. ///
  1521. /// // Insert a new Table after this Table.
  1522. /// Table newTable = t.InsertTableAfterSelf(2, 2);
  1523. /// newTable.Design = TableDesign.LightShadingAccent2;
  1524. /// newTable.Alignment = Alignment.center;
  1525. ///
  1526. /// // Save all changes made to this document.
  1527. /// document.Save();
  1528. /// }// Release this document from memory.
  1529. /// </code>
  1530. /// </example>
  1531. public override Table InsertTableAfterSelf( int rowCount, int columnCount )
  1532. {
  1533. return base.InsertTableAfterSelf( rowCount, columnCount );
  1534. }
  1535. /// <summary>
  1536. /// Insert a Paragraph before this Table, this Paragraph may have come from the same or another document.
  1537. /// </summary>
  1538. /// <param name="p">The Paragraph to insert.</param>
  1539. /// <returns>The Paragraph now associated with this document.</returns>
  1540. /// <example>
  1541. /// Take a Paragraph from document a, and insert it into document b before this Table.
  1542. /// <code>
  1543. /// // Place holder for a Paragraph.
  1544. /// Paragraph p;
  1545. ///
  1546. /// // Load document a.
  1547. /// using (DocX documentA = DocX.Load(@"a.docx"))
  1548. /// {
  1549. /// // Get the first paragraph from this document.
  1550. /// p = documentA.Paragraphs[0];
  1551. /// }
  1552. ///
  1553. /// // Load document b.
  1554. /// using (DocX documentB = DocX.Load(@"b.docx"))
  1555. /// {
  1556. /// // Get the first Table in document b.
  1557. /// Table t = documentB.Tables[0];
  1558. ///
  1559. /// // Insert the Paragraph from document a before this Table.
  1560. /// Paragraph newParagraph = t.InsertParagraphBeforeSelf(p);
  1561. ///
  1562. /// // Save all changes made to document b.
  1563. /// documentB.Save();
  1564. /// }// Release this document from memory.
  1565. /// </code>
  1566. /// </example>
  1567. public override Paragraph InsertParagraphBeforeSelf( Paragraph p )
  1568. {
  1569. return base.InsertParagraphBeforeSelf( p );
  1570. }
  1571. /// <summary>
  1572. /// Insert a new Paragraph before this Table.
  1573. /// </summary>
  1574. /// <param name="text">The initial text for this new Paragraph.</param>
  1575. /// <returns>A new Paragraph inserted before this Table.</returns>
  1576. /// <example>
  1577. /// Insert a new Paragraph before the first Table in this document.
  1578. /// <code>
  1579. /// // Create a new document.
  1580. /// using (DocX document = DocX.Create(@"Test.docx"))
  1581. /// {
  1582. /// // Insert a Table into this document.
  1583. /// Table t = document.InsertTable(2, 2);
  1584. ///
  1585. /// t.InsertParagraphBeforeSelf("I was inserted before the next Table.");
  1586. ///
  1587. /// // Save all changes made to this new document.
  1588. /// document.Save();
  1589. /// }// Release this new document form memory.
  1590. /// </code>
  1591. /// </example>
  1592. public override Paragraph InsertParagraphBeforeSelf( string text )
  1593. {
  1594. return base.InsertParagraphBeforeSelf( text );
  1595. }
  1596. /// <summary>
  1597. /// Insert a new Paragraph before this Table.
  1598. /// </summary>
  1599. /// <param name="text">The initial text for this new Paragraph.</param>
  1600. /// <param name="trackChanges">Should this insertion be tracked as a change?</param>
  1601. /// <returns>A new Paragraph inserted before this Table.</returns>
  1602. /// <example>
  1603. /// Insert a new paragraph before the first Table in this document.
  1604. /// <code>
  1605. /// // Create a new document.
  1606. /// using (DocX document = DocX.Create(@"Test.docx"))
  1607. /// {
  1608. /// // Insert a Table into this document.
  1609. /// Table t = document.InsertTable(2, 2);
  1610. ///
  1611. /// t.InsertParagraphBeforeSelf("I was inserted before the next Table.", false);
  1612. ///
  1613. /// // Save all changes made to this new document.
  1614. /// document.Save();
  1615. /// }// Release this new document form memory.
  1616. /// </code>
  1617. /// </example>
  1618. public override Paragraph InsertParagraphBeforeSelf( string text, bool trackChanges )
  1619. {
  1620. return base.InsertParagraphBeforeSelf( text, trackChanges );
  1621. }
  1622. /// <summary>
  1623. /// Insert a new Paragraph before this Table.
  1624. /// </summary>
  1625. /// <param name="text">The initial text for this new Paragraph.</param>
  1626. /// <param name="trackChanges">Should this insertion be tracked as a change?</param>
  1627. /// <param name="formatting">The formatting to apply to this insertion.</param>
  1628. /// <returns>A new Paragraph inserted before this Table.</returns>
  1629. /// <example>
  1630. /// Insert a new paragraph before the first Table in this document.
  1631. /// <code>
  1632. /// // Create a new document.
  1633. /// using (DocX document = DocX.Create(@"Test.docx"))
  1634. /// {
  1635. /// // Insert a Table into this document.
  1636. /// Table t = document.InsertTable(2, 2);
  1637. ///
  1638. /// Formatting boldFormatting = new Formatting();
  1639. /// boldFormatting.Bold = true;
  1640. ///
  1641. /// t.InsertParagraphBeforeSelf("I was inserted before the next Table.", false, boldFormatting);
  1642. ///
  1643. /// // Save all changes made to this new document.
  1644. /// document.Save();
  1645. /// }// Release this new document form memory.
  1646. /// </code>
  1647. /// </example>
  1648. public override Paragraph InsertParagraphBeforeSelf( string text, bool trackChanges, Formatting formatting )
  1649. {
  1650. return base.InsertParagraphBeforeSelf( text, trackChanges, formatting );
  1651. }
  1652. /// <summary>
  1653. /// Insert a Paragraph after this Table, this Paragraph may have come from the same or another document.
  1654. /// </summary>
  1655. /// <param name="p">The Paragraph to insert.</param>
  1656. /// <returns>The Paragraph now associated with this document.</returns>
  1657. /// <example>
  1658. /// Take a Paragraph from document a, and insert it into document b after this Table.
  1659. /// <code>
  1660. /// // Place holder for a Paragraph.
  1661. /// Paragraph p;
  1662. ///
  1663. /// // Load document a.
  1664. /// using (DocX documentA = DocX.Load(@"a.docx"))
  1665. /// {
  1666. /// // Get the first paragraph from this document.
  1667. /// p = documentA.Paragraphs[0];
  1668. /// }
  1669. ///
  1670. /// // Load document b.
  1671. /// using (DocX documentB = DocX.Load(@"b.docx"))
  1672. /// {
  1673. /// // Get the first Table in document b.
  1674. /// Table t = documentB.Tables[0];
  1675. ///
  1676. /// // Insert the Paragraph from document a after this Table.
  1677. /// Paragraph newParagraph = t.InsertParagraphAfterSelf(p);
  1678. ///
  1679. /// // Save all changes made to document b.
  1680. /// documentB.Save();
  1681. /// }// Release this document from memory.
  1682. /// </code>
  1683. /// </example>
  1684. public override Paragraph InsertParagraphAfterSelf( Paragraph p )
  1685. {
  1686. return base.InsertParagraphAfterSelf( p );
  1687. }
  1688. /// <summary>
  1689. /// Insert a new Paragraph after this Table.
  1690. /// </summary>
  1691. /// <param name="text">The initial text for this new Paragraph.</param>
  1692. /// <param name="trackChanges">Should this insertion be tracked as a change?</param>
  1693. /// <param name="formatting">The formatting to apply to this insertion.</param>
  1694. /// <returns>A new Paragraph inserted after this Table.</returns>
  1695. /// <example>
  1696. /// Insert a new paragraph after the first Table in this document.
  1697. /// <code>
  1698. /// // Create a new document.
  1699. /// using (DocX document = DocX.Create(@"Test.docx"))
  1700. /// {
  1701. /// // Insert a Table into this document.
  1702. /// Table t = document.InsertTable(2, 2);
  1703. ///
  1704. /// Formatting boldFormatting = new Formatting();
  1705. /// boldFormatting.Bold = true;
  1706. ///
  1707. /// t.InsertParagraphAfterSelf("I was inserted after the previous Table.", false, boldFormatting);
  1708. ///
  1709. /// // Save all changes made to this new document.
  1710. /// document.Save();
  1711. /// }// Release this new document form memory.
  1712. /// </code>
  1713. /// </example>
  1714. public override Paragraph InsertParagraphAfterSelf( string text, bool trackChanges, Formatting formatting )
  1715. {
  1716. return base.InsertParagraphAfterSelf( text, trackChanges, formatting );
  1717. }
  1718. /// <summary>
  1719. /// Insert a new Paragraph after this Table.
  1720. /// </summary>
  1721. /// <param name="text">The initial text for this new Paragraph.</param>
  1722. /// <param name="trackChanges">Should this insertion be tracked as a change?</param>
  1723. /// <returns>A new Paragraph inserted after this Table.</returns>
  1724. /// <example>
  1725. /// Insert a new paragraph after the first Table in this document.
  1726. /// <code>
  1727. /// // Create a new document.
  1728. /// using (DocX document = DocX.Create(@"Test.docx"))
  1729. /// {
  1730. /// // Insert a Table into this document.
  1731. /// Table t = document.InsertTable(2, 2);
  1732. ///
  1733. /// t.InsertParagraphAfterSelf("I was inserted after the previous Table.", false);
  1734. ///
  1735. /// // Save all changes made to this new document.
  1736. /// document.Save();
  1737. /// }// Release this new document form memory.
  1738. /// </code>
  1739. /// </example>
  1740. public override Paragraph InsertParagraphAfterSelf( string text, bool trackChanges )
  1741. {
  1742. return base.InsertParagraphAfterSelf( text, trackChanges );
  1743. }
  1744. /// <summary>
  1745. /// Insert a new Paragraph after this Table.
  1746. /// </summary>
  1747. /// <param name="text">The initial text for this new Paragraph.</param>
  1748. /// <returns>A new Paragraph inserted after this Table.</returns>
  1749. /// <example>
  1750. /// Insert a new Paragraph after the first Table in this document.
  1751. /// <code>
  1752. /// // Create a new document.
  1753. /// using (DocX document = DocX.Create(@"Test.docx"))
  1754. /// {
  1755. /// // Insert a Table into this document.
  1756. /// Table t = document.InsertTable(2, 2);
  1757. ///
  1758. /// t.InsertParagraphAfterSelf("I was inserted after the previous Table.");
  1759. ///
  1760. /// // Save all changes made to this new document.
  1761. /// document.Save();
  1762. /// }// Release this new document form memory.
  1763. /// </code>
  1764. /// </example>
  1765. public override Paragraph InsertParagraphAfterSelf( string text )
  1766. {
  1767. return base.InsertParagraphAfterSelf( text );
  1768. }
  1769. /// <summary>
  1770. /// Set a table border
  1771. /// </summary>
  1772. /// <example>
  1773. /// <code>
  1774. /// // Create a new document.
  1775. ///using (DocX document = DocX.Create("Test.docx"))
  1776. ///{
  1777. /// // Insert a table into this document.
  1778. /// Table t = document.InsertTable(3, 3);
  1779. ///
  1780. /// // Create a large blue border.
  1781. /// Border b = new Border(BorderStyle.Tcbs_single, BorderSize.seven, 0, Color.Blue);
  1782. ///
  1783. /// // Set the tables Top, Bottom, Left and Right Borders to b.
  1784. /// t.SetBorder(TableBorderType.Top, b);
  1785. /// t.SetBorder(TableBorderType.Bottom, b);
  1786. /// t.SetBorder(TableBorderType.Left, b);
  1787. /// t.SetBorder(TableBorderType.Right, b);
  1788. ///
  1789. /// // Save the document.
  1790. /// document.Save();
  1791. ///}
  1792. /// </code>
  1793. /// </example>
  1794. /// <param name="borderType">The table border to set</param>
  1795. /// <param name="border">Border object to set the table border</param>
  1796. public void SetBorder( TableBorderType borderType, Border border )
  1797. {
  1798. /*
  1799. * Get the tblPr (table properties) element for this Table,
  1800. * null will be return if no such element exists.
  1801. */
  1802. var tblPr = Xml.Element( XName.Get( "tblPr", DocX.w.NamespaceName ) );
  1803. if( tblPr == null )
  1804. {
  1805. this.Xml.SetElementValue( XName.Get( "tblPr", DocX.w.NamespaceName ), string.Empty );
  1806. tblPr = Xml.Element( XName.Get( "tblPr", DocX.w.NamespaceName ) );
  1807. }
  1808. /*
  1809. * Get the tblBorders (table borders) element for this Table,
  1810. * null will be return if no such element exists.
  1811. */
  1812. var tblBorders = tblPr.Element( XName.Get( "tblBorders", DocX.w.NamespaceName ) );
  1813. if( tblBorders == null )
  1814. {
  1815. tblPr.SetElementValue( XName.Get( "tblBorders", DocX.w.NamespaceName ), string.Empty );
  1816. tblBorders = tblPr.Element( XName.Get( "tblBorders", DocX.w.NamespaceName ) );
  1817. }
  1818. /*
  1819. * Get the 'borderType' (table border) element for this Table,
  1820. * null will be return if no such element exists.
  1821. */
  1822. string tbordertype;
  1823. tbordertype = borderType.ToString();
  1824. // only lower the first char of string (because of insideH and insideV)
  1825. tbordertype = tbordertype.Substring( 0, 1 ).ToLower() + tbordertype.Substring( 1 );
  1826. var tblBorderType = tblBorders.Element( XName.Get( borderType.ToString(), DocX.w.NamespaceName ) );
  1827. if( tblBorderType == null )
  1828. {
  1829. tblBorders.SetElementValue( XName.Get( tbordertype, DocX.w.NamespaceName ), string.Empty );
  1830. tblBorderType = tblBorders.Element( XName.Get( tbordertype, DocX.w.NamespaceName ) );
  1831. }
  1832. // get string value of border style
  1833. var borderstyle = border.Tcbs.ToString().Substring( 5 );
  1834. borderstyle = borderstyle.Substring( 0, 1 ).ToLower() + borderstyle.Substring( 1 );
  1835. // The val attribute is used for the border style
  1836. tblBorderType.SetAttributeValue( XName.Get( "val", DocX.w.NamespaceName ), borderstyle );
  1837. if( border.Tcbs != BorderStyle.Tcbs_nil )
  1838. {
  1839. int size;
  1840. switch( border.Size )
  1841. {
  1842. case BorderSize.one:
  1843. size = 2;
  1844. break;
  1845. case BorderSize.two:
  1846. size = 4;
  1847. break;
  1848. case BorderSize.three:
  1849. size = 6;
  1850. break;
  1851. case BorderSize.four:
  1852. size = 8;
  1853. break;
  1854. case BorderSize.five:
  1855. size = 12;
  1856. break;
  1857. case BorderSize.six:
  1858. size = 18;
  1859. break;
  1860. case BorderSize.seven:
  1861. size = 24;
  1862. break;
  1863. case BorderSize.eight:
  1864. size = 36;
  1865. break;
  1866. case BorderSize.nine:
  1867. size = 48;
  1868. break;
  1869. default:
  1870. size = 2;
  1871. break;
  1872. }
  1873. // The sz attribute is used for the border size
  1874. tblBorderType.SetAttributeValue( XName.Get( "sz", DocX.w.NamespaceName ), ( size ).ToString() );
  1875. // The space attribute is used for the cell spacing (probably '0')
  1876. tblBorderType.SetAttributeValue( XName.Get( "space", DocX.w.NamespaceName ), ( border.Space ).ToString() );
  1877. // The color attribute is used for the border color
  1878. tblBorderType.SetAttributeValue( XName.Get( "color", DocX.w.NamespaceName ), border.Color.ToHex() );
  1879. }
  1880. }
  1881. /// <summary>
  1882. /// Get a table border
  1883. /// </summary>
  1884. /// <param name="borderType">The table border to get</param>
  1885. public Border GetBorder( TableBorderType borderType )
  1886. {
  1887. // instance with default border values
  1888. var b = new Border();
  1889. /*
  1890. * Get the tblPr (table properties) element for this Table,
  1891. * null will be return if no such element exists.
  1892. */
  1893. var tblPr = Xml.Element( XName.Get( "tblPr", DocX.w.NamespaceName ) );
  1894. if( tblPr == null )
  1895. {
  1896. // uses default border style
  1897. }
  1898. /*
  1899. * Get the tblBorders (table borders) element for this Table,
  1900. * null will be return if no such element exists.
  1901. */
  1902. var tblBorders = tblPr.Element( XName.Get( "tblBorders", DocX.w.NamespaceName ) );
  1903. if( tblBorders == null )
  1904. {
  1905. // uses default border style
  1906. }
  1907. /*
  1908. * Get the 'borderType' (table border) element for this Table,
  1909. * null will be return if no such element exists.
  1910. */
  1911. string tbordertype = borderType.ToString();
  1912. // only lower the first char of string (because of insideH and insideV)
  1913. tbordertype = tbordertype.Substring( 0, 1 ).ToLower() + tbordertype.Substring( 1 );
  1914. var tblBorderType = tblBorders.Element( XName.Get( tbordertype, DocX.w.NamespaceName ) );
  1915. if( tblBorderType == null )
  1916. {
  1917. // uses default border style
  1918. }
  1919. // The val attribute is used for the border style
  1920. var val = tblBorderType.Attribute( XName.Get( "val", DocX.w.NamespaceName ) );
  1921. // If val is null, this table contains no border information.
  1922. if( val == null )
  1923. {
  1924. // uses default border style
  1925. }
  1926. else
  1927. {
  1928. try
  1929. {
  1930. var bordertype = "Tcbs_" + val.Value;
  1931. b.Tcbs = ( BorderStyle )Enum.Parse( typeof( BorderStyle ), bordertype );
  1932. }
  1933. catch
  1934. {
  1935. val.Remove();
  1936. // uses default border style
  1937. }
  1938. }
  1939. // The sz attribute is used for the border size
  1940. var sz = tblBorderType.Attribute( XName.Get( "sz", DocX.w.NamespaceName ) );
  1941. // If sz is null, this border contains no size information.
  1942. if( sz == null )
  1943. {
  1944. // uses default border style
  1945. }
  1946. else
  1947. {
  1948. // If sz is not an int, something is wrong with this attributes value, so remove it
  1949. int numerical_size;
  1950. if( !int.TryParse( sz.Value, out numerical_size ) )
  1951. {
  1952. sz.Remove();
  1953. }
  1954. else
  1955. {
  1956. switch( numerical_size )
  1957. {
  1958. case 2:
  1959. b.Size = BorderSize.one;
  1960. break;
  1961. case 4:
  1962. b.Size = BorderSize.two;
  1963. break;
  1964. case 6:
  1965. b.Size = BorderSize.three;
  1966. break;
  1967. case 8:
  1968. b.Size = BorderSize.four;
  1969. break;
  1970. case 12:
  1971. b.Size = BorderSize.five;
  1972. break;
  1973. case 18:
  1974. b.Size = BorderSize.six;
  1975. break;
  1976. case 24:
  1977. b.Size = BorderSize.seven;
  1978. break;
  1979. case 36:
  1980. b.Size = BorderSize.eight;
  1981. break;
  1982. case 48:
  1983. b.Size = BorderSize.nine;
  1984. break;
  1985. default:
  1986. b.Size = BorderSize.one;
  1987. break;
  1988. }
  1989. }
  1990. }
  1991. // The space attribute is used for the border spacing (probably '0')
  1992. var space = tblBorderType.Attribute( XName.Get( "space", DocX.w.NamespaceName ) );
  1993. // If space is null, this border contains no space information.
  1994. if( space == null )
  1995. {
  1996. // uses default border style
  1997. }
  1998. else
  1999. {
  2000. // If space is not an int, something is wrong with this attributes value, so remove it
  2001. int borderspace;
  2002. if( !int.TryParse( space.Value, out borderspace ) )
  2003. {
  2004. space.Remove();
  2005. // uses default border style
  2006. }
  2007. else
  2008. {
  2009. b.Space = borderspace;
  2010. }
  2011. }
  2012. // The color attribute is used for the border color
  2013. var color = tblBorderType.Attribute( XName.Get( "color", DocX.w.NamespaceName ) );
  2014. if( color == null )
  2015. {
  2016. // uses default border style
  2017. }
  2018. else
  2019. {
  2020. // If color is not a Color, something is wrong with this attributes value, so remove it
  2021. try
  2022. {
  2023. b.Color = ColorTranslator.FromHtml( string.Format( "#{0}", color.Value ) );
  2024. }
  2025. catch
  2026. {
  2027. color.Remove();
  2028. // uses default border style
  2029. }
  2030. }
  2031. return b;
  2032. }
  2033. public Double GetColumnWidth( Int32 columnIndex )
  2034. {
  2035. List<Double> columnWidths = ColumnWidths;
  2036. if( columnWidths == null || columnIndex > columnWidths.Count - 1 )
  2037. return Double.NaN;
  2038. return columnWidths[ columnIndex ];
  2039. }
  2040. public void SetColumnWidth( int columnIndex, double width )
  2041. {
  2042. var columnWidths = this.ColumnWidths;
  2043. if( columnWidths == null || ( columnIndex > columnWidths.Count - 1 ) )
  2044. {
  2045. if( this.Rows.Count == 0 )
  2046. throw new Exception( "There is at least one row required to detect the existing columns." );
  2047. columnWidths = new List<Double>();
  2048. foreach( Cell c in Rows[ Rows.Count - 1 ].Cells )
  2049. {
  2050. columnWidths.Add( c.Width );
  2051. }
  2052. }
  2053. // check if the columnIndex is valid
  2054. if( columnIndex > (columnWidths.Count - 1) )
  2055. throw new Exception( "The index is greather than the available table columns." );
  2056. // append a new grid if null
  2057. var grid = Xml.Element( XName.Get( "tblGrid", DocX.w.NamespaceName ) );
  2058. if( grid == null )
  2059. {
  2060. var tblPr = GetOrCreate_tblPr();
  2061. tblPr.AddAfterSelf( new XElement( XName.Get( "tblGrid", DocX.w.NamespaceName ) ) );
  2062. grid = Xml.Element( XName.Get( "tblGrid", DocX.w.NamespaceName ) );
  2063. }
  2064. // remove all existing values
  2065. grid?.RemoveAll();
  2066. // append new column widths
  2067. int index = 0;
  2068. foreach( var columnWidth in columnWidths )
  2069. {
  2070. double newWidth = columnWidth;
  2071. if( index == columnIndex )
  2072. {
  2073. newWidth = width;
  2074. }
  2075. var newColumn = new XElement( XName.Get( "gridCol", DocX.w.NamespaceName ), new XAttribute( XName.Get( "w", DocX.w.NamespaceName ), newWidth ) );
  2076. grid?.Add( newColumn );
  2077. index += 1;
  2078. }
  2079. // remove cell widths
  2080. foreach( Row row in this.Rows )
  2081. {
  2082. foreach( Cell cell in row.Cells )
  2083. {
  2084. cell.Width = -1;
  2085. }
  2086. }
  2087. // set AutoFit to Fixed
  2088. this.AutoFit = AutoFit.Fixed;
  2089. }
  2090. public List<Double> ColumnWidths
  2091. {
  2092. get
  2093. {
  2094. var columnWidths = new List<Double>();
  2095. // get the table grid property
  2096. XElement grid = Xml.Element( XName.Get( "tblGrid", DocX.w.NamespaceName ) );
  2097. // get the columns properties
  2098. var columns = grid?.Elements( XName.Get( "gridCol", DocX.w.NamespaceName ) );
  2099. if( columns == null )
  2100. return null;
  2101. foreach( var column in columns )
  2102. {
  2103. string value = column.GetAttribute( XName.Get( "w", DocX.w.NamespaceName ) );
  2104. columnWidths.Add( Convert.ToDouble( value, new CultureInfo("en-US" ) ) );
  2105. }
  2106. return columnWidths;
  2107. }
  2108. }
  2109. public void SetTableCellMargin( TableCellMarginType type, double margin )
  2110. {
  2111. var tblPr = this.GetOrCreate_tblPr();
  2112. var tblCellMarXName = XName.Get( "tblCellMar", DocX.w.NamespaceName );
  2113. var typeXName = XName.Get( type.ToString(), DocX.w.NamespaceName );
  2114. var tblCellMar = tblPr.Element( tblCellMarXName );
  2115. if( tblCellMar == null )
  2116. {
  2117. tblPr.AddFirst( new XElement( tblCellMarXName ) );
  2118. tblCellMar = tblPr.Element( tblCellMarXName );
  2119. }
  2120. var side = tblCellMar.Element( typeXName );
  2121. if( side == null )
  2122. {
  2123. tblCellMar.AddFirst( new XElement( typeXName ) );
  2124. side = tblCellMar.Element( typeXName );
  2125. }
  2126. side.RemoveAttributes();
  2127. // Set value and side for cell Margin
  2128. side.Add( new XAttribute( XName.Get( "w", DocX.w.NamespaceName ), margin ) );
  2129. side.Add( new XAttribute( XName.Get( "type", DocX.w.NamespaceName ), "dxa" ) );
  2130. }
  2131. /// <summary>
  2132. /// Deletes a cell in a row and shift the others to the left.
  2133. /// </summary>
  2134. /// <param name="rowIndex">index of the row where a cell will be removed.</param>
  2135. /// <param name="celIndex">index of the cell to remove in the row.</param>
  2136. public void DeleteAndShiftCellsLeft( int rowIndex, int celIndex )
  2137. {
  2138. var trPr = this.Rows[ rowIndex ].Xml.Element( XName.Get( "trPr", DocX.w.NamespaceName ) );
  2139. if( trPr != null )
  2140. {
  2141. var gridAfter = trPr.Element( XName.Get( "gridAfter", DocX.w.NamespaceName ) );
  2142. if( gridAfter != null )
  2143. {
  2144. var gridAfterValAttr = gridAfter.Attribute( XName.Get( "val", DocX.w.NamespaceName ) );
  2145. gridAfterValAttr.Value = ( gridAfterValAttr != null ) ? int.Parse( gridAfterValAttr.Value ).ToString() : "1";
  2146. }
  2147. else
  2148. {
  2149. gridAfter.SetAttributeValue( "val", 1 );
  2150. }
  2151. }
  2152. else
  2153. {
  2154. var gridAfterXElement = new XElement( XName.Get( "gridAfter", DocX.w.NamespaceName ) );
  2155. var valXAttribute = new XAttribute( XName.Get( "val", DocX.w.NamespaceName ), 1 );
  2156. gridAfterXElement.Add( valXAttribute );
  2157. var trPrXElement = new XElement( XName.Get( "trPr", DocX.w.NamespaceName ) );
  2158. trPrXElement.Add( gridAfterXElement );
  2159. this.Rows[ rowIndex ].Xml.AddFirst( trPrXElement );
  2160. }
  2161. if( ( celIndex <= this.ColumnCount ) && ( this.Rows[ rowIndex ].ColumnCount <= this.ColumnCount ) )
  2162. {
  2163. this.Rows[ rowIndex ].Cells[ celIndex ].Xml.Remove();
  2164. }
  2165. }
  2166. #endregion
  2167. #region Internal Methods
  2168. /// <summary>
  2169. /// If the tblPr element doesent exist it is created, either way it is returned by this function.
  2170. /// </summary>
  2171. /// <returns>The tblPr element for this Table.</returns>
  2172. internal XElement GetOrCreate_tblPr()
  2173. {
  2174. // Get the element.
  2175. var tblPr = Xml.Element( XName.Get( "tblPr", DocX.w.NamespaceName ) );
  2176. // If it dosen't exist, create it.
  2177. if( tblPr == null )
  2178. {
  2179. this.Xml.AddFirst( new XElement( XName.Get( "tblPr", DocX.w.NamespaceName ) ) );
  2180. tblPr = Xml.Element( XName.Get( "tblPr", DocX.w.NamespaceName ) );
  2181. }
  2182. // Return the pPr element for this Paragraph.
  2183. return tblPr;
  2184. }
  2185. #endregion
  2186. #region Private Methods
  2187. private Row InsertRow( List<XElement> content, Int32 index )
  2188. {
  2189. Row newRow = new Row( this, Document, new XElement( XName.Get( "tr", DocX.w.NamespaceName ), content ) );
  2190. XElement rowXml;
  2191. if( index == Rows.Count )
  2192. {
  2193. rowXml = Rows.Last().Xml;
  2194. rowXml.AddAfterSelf( newRow.Xml );
  2195. }
  2196. else
  2197. {
  2198. rowXml = Rows[ index ].Xml;
  2199. rowXml.AddBeforeSelf( newRow.Xml );
  2200. }
  2201. return newRow;
  2202. }
  2203. private void AddCellToRow( Row row, XElement cell, int index, bool direction )
  2204. {
  2205. if( index >= row.Cells.Count )
  2206. throw new IndexOutOfRangeException( "index is greater or equals to row.Cells.Count." );
  2207. if( direction )
  2208. {
  2209. row.Cells[ index ].Xml.AddAfterSelf( cell );
  2210. }
  2211. else
  2212. {
  2213. row.Cells[ index ].Xml.AddBeforeSelf( cell );
  2214. }
  2215. }
  2216. #endregion
  2217. }
  2218. /// <summary>
  2219. /// Represents a single row in a Table.
  2220. /// </summary>
  2221. public class Row : Container
  2222. {
  2223. #region Internal Members
  2224. internal Table _table;
  2225. #endregion
  2226. #region Public Properties
  2227. /// <summary>
  2228. /// Calculates columns count in the row, taking spanned cells into account
  2229. /// </summary>
  2230. public Int32 ColumnCount
  2231. {
  2232. get
  2233. {
  2234. int gridSpanSum = this.GridAfter;
  2235. // Foreach each Cell between startIndex and endIndex inclusive.
  2236. foreach( Cell c in Cells )
  2237. {
  2238. if( c.GridSpan != 0 )
  2239. {
  2240. gridSpanSum += (c.GridSpan - 1);
  2241. }
  2242. }
  2243. // return cells count + count of spanned cells
  2244. return Cells.Count + gridSpanSum;
  2245. }
  2246. }
  2247. /// <summary>
  2248. /// Returns the row.GridAfter => The number of deleted cells in a row.
  2249. /// </summary>
  2250. public int GridAfter
  2251. {
  2252. get
  2253. {
  2254. var trPr = this.Xml.Element( XName.Get( "trPr", DocX.w.NamespaceName ) );
  2255. if( trPr != null )
  2256. {
  2257. var gridAfter = trPr.Element( XName.Get( "gridAfter", DocX.w.NamespaceName ) );
  2258. var gridAfterAttrVal = gridAfter?.Attribute( XName.Get( "val", DocX.w.NamespaceName ) );
  2259. if( gridAfterAttrVal != null )
  2260. {
  2261. return int.Parse( gridAfterAttrVal.Value );
  2262. }
  2263. }
  2264. return 0;
  2265. }
  2266. }
  2267. /// <summary>
  2268. /// A list of Cells in this Row.
  2269. /// </summary>
  2270. public List<Cell> Cells
  2271. {
  2272. get
  2273. {
  2274. List<Cell> cells =
  2275. (
  2276. from c in Xml.Elements( XName.Get( "tc", DocX.w.NamespaceName ) )
  2277. select new Cell( this, Document, c )
  2278. ).ToList();
  2279. return cells;
  2280. }
  2281. }
  2282. public override ReadOnlyCollection<Paragraph> Paragraphs
  2283. {
  2284. get
  2285. {
  2286. var paragraphs =
  2287. (
  2288. from p in Xml.Descendants( DocX.w + "p" )
  2289. select new Paragraph( Document, p, 0 )
  2290. ).ToList();
  2291. foreach( Paragraph p in paragraphs )
  2292. {
  2293. p.PackagePart = _table.PackagePart;
  2294. }
  2295. return paragraphs.AsReadOnly();
  2296. }
  2297. }
  2298. /// <summary>
  2299. /// Height in pixels.
  2300. /// </summary>
  2301. public double Height
  2302. {
  2303. get
  2304. {
  2305. /*
  2306. * Get the trPr (table row properties) element for this Row,
  2307. * null will be return if no such element exists.
  2308. */
  2309. XElement trPr = Xml.Element( XName.Get( "trPr", DocX.w.NamespaceName ) );
  2310. // If trPr is null, this row contains no height information.
  2311. // Get the trHeight element for this Row,
  2312. // null will be return if no such element exists.
  2313. XElement trHeight = trPr?.Element( XName.Get( "trHeight", DocX.w.NamespaceName ) );
  2314. // If trHeight is null, this row contains no height information.
  2315. // Get the val attribute for this trHeight element.
  2316. XAttribute val = trHeight?.Attribute( XName.Get( "val", DocX.w.NamespaceName ) );
  2317. // If w is null, this cell contains no width information.
  2318. if( val == null )
  2319. return double.NaN;
  2320. // If val is not a double, something is wrong with this attributes value, so remove it and return double.NaN;
  2321. double heightInWordUnits;
  2322. if( !double.TryParse( val.Value, out heightInWordUnits ) )
  2323. {
  2324. val.Remove();
  2325. return double.NaN;
  2326. }
  2327. // Using 20 to match DocX._pageSizeMultiplier.
  2328. return ( heightInWordUnits / 20 );
  2329. }
  2330. set
  2331. {
  2332. SetHeight( value, true );
  2333. }
  2334. }
  2335. /// <summary>
  2336. /// Minimum Height in pixels.
  2337. /// </summary>
  2338. public double MinHeight
  2339. {
  2340. get
  2341. {
  2342. return Height;
  2343. }
  2344. set
  2345. {
  2346. SetHeight( value, false );
  2347. }
  2348. }
  2349. public bool TableHeader
  2350. {
  2351. get
  2352. {
  2353. XElement trPr = Xml.Element( XName.Get( "trPr", DocX.w.NamespaceName ) );
  2354. XElement tblHeader = trPr?.Element( XName.Get( "tblHeader", DocX.w.NamespaceName ) );
  2355. return tblHeader != null;
  2356. }
  2357. set
  2358. {
  2359. XElement trPr = Xml.Element( XName.Get( "trPr", DocX.w.NamespaceName ) );
  2360. if( trPr == null )
  2361. {
  2362. Xml.SetElementValue( XName.Get( "trPr", DocX.w.NamespaceName ), string.Empty );
  2363. trPr = Xml.Element( XName.Get( "trPr", DocX.w.NamespaceName ) );
  2364. }
  2365. XElement tblHeader = trPr.Element( XName.Get( "tblHeader", DocX.w.NamespaceName ) );
  2366. if( tblHeader == null && value )
  2367. trPr.SetElementValue( XName.Get( "tblHeader", DocX.w.NamespaceName ), string.Empty );
  2368. if( tblHeader != null && !value )
  2369. tblHeader.Remove();
  2370. }
  2371. }
  2372. /// <summary>
  2373. /// Allow row to break across pages.
  2374. /// Default value is True : Word will break the contents of the row across the pages.
  2375. /// When False, the contents of the row will not be split across the pages; it will be entirely moved to the next page.
  2376. /// </summary>
  2377. public bool BreakAcrossPages
  2378. {
  2379. get
  2380. {
  2381. var trPr = Xml.Element( XName.Get( "trPr", DocX.w.NamespaceName ) );
  2382. var cantSplit = trPr?.Element( XName.Get( "cantSplit", DocX.w.NamespaceName ) );
  2383. return cantSplit == null;
  2384. }
  2385. set
  2386. {
  2387. var trPrXName = XName.Get( "trPr", DocX.w.NamespaceName );
  2388. var cantSplitXName = XName.Get( "cantSplit", DocX.w.NamespaceName );
  2389. if( value )
  2390. {
  2391. var trPr = Xml.Element( trPrXName );
  2392. var cantSplit = trPr?.Element( cantSplitXName );
  2393. if( cantSplit != null )
  2394. cantSplit.Remove();
  2395. }
  2396. else
  2397. {
  2398. var trPr = Xml.Element( trPrXName );
  2399. if( trPr == null )
  2400. {
  2401. Xml.SetElementValue( trPrXName, string.Empty );
  2402. trPr = Xml.Element( trPrXName );
  2403. }
  2404. var cantSplit = trPr.Element( cantSplitXName );
  2405. if( cantSplit == null )
  2406. {
  2407. trPr.SetElementValue( cantSplitXName, string.Empty );
  2408. }
  2409. }
  2410. }
  2411. }
  2412. #endregion
  2413. #region Constructors
  2414. internal Row( Table table, DocX document, XElement xml )
  2415. : base( document, xml )
  2416. {
  2417. _table = table;
  2418. this.PackagePart = table.PackagePart;
  2419. }
  2420. #endregion
  2421. #region Private Methods
  2422. private void SetHeight( double height, bool isHeightExact )
  2423. {
  2424. XElement trPr = Xml.Element( XName.Get( "trPr", DocX.w.NamespaceName ) );
  2425. if( trPr == null )
  2426. {
  2427. Xml.SetElementValue( XName.Get( "trPr", DocX.w.NamespaceName ), string.Empty );
  2428. trPr = Xml.Element( XName.Get( "trPr", DocX.w.NamespaceName ) );
  2429. }
  2430. XElement trHeight = trPr.Element( XName.Get( "trHeight", DocX.w.NamespaceName ) );
  2431. if( trHeight == null )
  2432. {
  2433. trPr.SetElementValue( XName.Get( "trHeight", DocX.w.NamespaceName ), string.Empty );
  2434. trHeight = trPr.Element( XName.Get( "trHeight", DocX.w.NamespaceName ) );
  2435. }
  2436. // The hRule attribute needs to be set.
  2437. trHeight.SetAttributeValue( XName.Get( "hRule", DocX.w.NamespaceName ), isHeightExact ? "exact" : "atLeast" );
  2438. // Using 20 to match DocX._pageSizeMultiplier.
  2439. trHeight.SetAttributeValue( XName.Get( "val", DocX.w.NamespaceName ), ( height * 20 ).ToString() );
  2440. }
  2441. #endregion
  2442. #region Public Methods
  2443. public void Remove()
  2444. {
  2445. XElement table = Xml.Parent;
  2446. Xml.Remove();
  2447. if( !table.Elements( XName.Get( "tr", DocX.w.NamespaceName ) ).Any() )
  2448. table.Remove();
  2449. }
  2450. /// <summary>
  2451. /// Merge cells starting with startIndex and ending with endIndex.
  2452. /// </summary>
  2453. public void MergeCells( int startIndex, int endIndex )
  2454. {
  2455. // Check for valid start and end indexes.
  2456. if( startIndex < 0 || endIndex <= startIndex || endIndex > Cells.Count + 1 )
  2457. throw new IndexOutOfRangeException();
  2458. // The sum of all merged gridSpans.
  2459. int gridSpanSum = 0;
  2460. // Foreach each Cell between startIndex and endIndex inclusive.
  2461. foreach( Cell c in Cells.Where( ( z, i ) => i > startIndex && i <= endIndex ) )
  2462. {
  2463. XElement tcPr = c.Xml.Element( XName.Get( "tcPr", DocX.w.NamespaceName ) );
  2464. XElement gridSpan = tcPr?.Element( XName.Get( "gridSpan", DocX.w.NamespaceName ) );
  2465. if( gridSpan != null )
  2466. {
  2467. XAttribute val = gridSpan.Attribute( XName.Get( "val", DocX.w.NamespaceName ) );
  2468. int value;
  2469. if( val != null && int.TryParse( val.Value, out value ) )
  2470. gridSpanSum += value - 1;
  2471. }
  2472. // Add this cells Pragraph to the merge start Cell.
  2473. Cells[ startIndex ].Xml.Add( c.Xml.Elements( XName.Get( "p", DocX.w.NamespaceName ) ) );
  2474. // Remove this Cell.
  2475. c.Xml.Remove();
  2476. }
  2477. // Trim cell's paragraphs to remove extra blank lines, if any
  2478. int index = 0;
  2479. do
  2480. {
  2481. // If the cell doesn't have multiple paragraphs, leave the loop
  2482. if ( Cells[ startIndex ].Paragraphs.Count < 2 )
  2483. break;
  2484. // Remove the last paragraph if it's a blank line, otherwise trimming is done
  2485. index = Cells[ startIndex ].Paragraphs.Count - 1;
  2486. if ( Cells[ startIndex ].Paragraphs[ index ].Text.Trim() == "" )
  2487. Cells[ startIndex ].Paragraphs[ index ].Remove( false );
  2488. else
  2489. break;
  2490. } while( true );
  2491. /*
  2492. * Get the tcPr (table cell properties) element for the first cell in this merge,
  2493. * null will be returned if no such element exists.
  2494. */
  2495. XElement start_tcPr = Cells[ startIndex ].Xml.Element( XName.Get( "tcPr", DocX.w.NamespaceName ) );
  2496. if( start_tcPr == null )
  2497. {
  2498. Cells[ startIndex ].Xml.SetElementValue( XName.Get( "tcPr", DocX.w.NamespaceName ), string.Empty );
  2499. start_tcPr = Cells[ startIndex ].Xml.Element( XName.Get( "tcPr", DocX.w.NamespaceName ) );
  2500. }
  2501. /*
  2502. * Get the gridSpan element of this row,
  2503. * null will be returned if no such element exists.
  2504. */
  2505. XElement start_gridSpan = start_tcPr.Element( XName.Get( "gridSpan", DocX.w.NamespaceName ) );
  2506. if( start_gridSpan == null )
  2507. {
  2508. start_tcPr.SetElementValue( XName.Get( "gridSpan", DocX.w.NamespaceName ), string.Empty );
  2509. start_gridSpan = start_tcPr.Element( XName.Get( "gridSpan", DocX.w.NamespaceName ) );
  2510. }
  2511. /*
  2512. * Get the val attribute of this row,
  2513. * null will be returned if no such element exists.
  2514. */
  2515. XAttribute start_val = start_gridSpan.Attribute( XName.Get( "val", DocX.w.NamespaceName ) );
  2516. int start_value = 0;
  2517. if( start_val != null )
  2518. if( int.TryParse( start_val.Value, out start_value ) )
  2519. gridSpanSum += start_value - 1;
  2520. // Set the val attribute to the number of merged cells.
  2521. start_gridSpan.SetAttributeValue( XName.Get( "val", DocX.w.NamespaceName ), ( gridSpanSum + ( endIndex - startIndex + 1 ) ).ToString() );
  2522. }
  2523. #endregion
  2524. }
  2525. public class Cell : Container
  2526. {
  2527. #region Internal Members
  2528. internal Row _row;
  2529. #endregion
  2530. #region Public Properties
  2531. public override ReadOnlyCollection<Paragraph> Paragraphs
  2532. {
  2533. get
  2534. {
  2535. var paragraphs = base.Paragraphs;
  2536. foreach( Paragraph p in paragraphs )
  2537. {
  2538. p.PackagePart = _row._table.PackagePart;
  2539. }
  2540. return paragraphs;
  2541. }
  2542. }
  2543. /// <summary>
  2544. /// Gets or Sets this Cells vertical alignment.
  2545. /// </summary>
  2546. /// <example>
  2547. /// Creates a table with 3 cells and sets the vertical alignment of each to 1 of the 3 available options.
  2548. /// <code>
  2549. ///// Create a new document.
  2550. ///using(DocX document = DocX.Create("Test.docx"))
  2551. ///{
  2552. /// // Insert a Table into this document.
  2553. /// Table t = document.InsertTable(3, 1);
  2554. ///
  2555. /// // Set the design of the Table such that we can easily identify cell boundaries.
  2556. /// t.Design = TableDesign.TableGrid;
  2557. ///
  2558. /// // Set the height of the row bigger than default.
  2559. /// // We need to be able to see the difference in vertical cell alignment options.
  2560. /// t.Rows[0].Height = 100;
  2561. ///
  2562. /// // Set the vertical alignment of cell0 to top.
  2563. /// Cell c0 = t.Rows[0].Cells[0];
  2564. /// c0.InsertParagraph("VerticalAlignment.Top");
  2565. /// c0.VerticalAlignment = VerticalAlignment.Top;
  2566. ///
  2567. /// // Set the vertical alignment of cell1 to center.
  2568. /// Cell c1 = t.Rows[0].Cells[1];
  2569. /// c1.InsertParagraph("VerticalAlignment.Center");
  2570. /// c1.VerticalAlignment = VerticalAlignment.Center;
  2571. ///
  2572. /// // Set the vertical alignment of cell2 to bottom.
  2573. /// Cell c2 = t.Rows[0].Cells[2];
  2574. /// c2.InsertParagraph("VerticalAlignment.Bottom");
  2575. /// c2.VerticalAlignment = VerticalAlignment.Bottom;
  2576. ///
  2577. /// // Save the document.
  2578. /// document.Save();
  2579. ///}
  2580. /// </code>
  2581. /// </example>
  2582. public VerticalAlignment VerticalAlignment
  2583. {
  2584. get
  2585. {
  2586. /*
  2587. * Get the tcPr (table cell properties) element for this Cell,
  2588. * null will be return if no such element exists.
  2589. */
  2590. XElement tcPr = Xml.Element( XName.Get( "tcPr", DocX.w.NamespaceName ) );
  2591. // If tcPr is null, this cell contains no width information.
  2592. // Get the vAlign (table cell vertical alignment) element for this Cell,
  2593. // null will be return if no such element exists.
  2594. XElement vAlign = tcPr?.Element( XName.Get( "vAlign", DocX.w.NamespaceName ) );
  2595. // If vAlign is null, this cell contains no vertical alignment information.
  2596. // Get the val attribute of the vAlign element.
  2597. XAttribute val = vAlign?.Attribute( XName.Get( "val", DocX.w.NamespaceName ) );
  2598. // If val is null, this cell contains no vAlign information.
  2599. if( val == null )
  2600. return VerticalAlignment.Center;
  2601. // If val is not a VerticalAlign enum, something is wrong with this attributes value, so remove it and return VerticalAlignment.Center;
  2602. try
  2603. {
  2604. return ( VerticalAlignment )Enum.Parse( typeof( VerticalAlignment ), val.Value, true );
  2605. }
  2606. catch
  2607. {
  2608. val.Remove();
  2609. return VerticalAlignment.Center;
  2610. }
  2611. }
  2612. set
  2613. {
  2614. /*
  2615. * Get the tcPr (table cell properties) element for this Cell,
  2616. * null will be return if no such element exists.
  2617. */
  2618. XElement tcPr = Xml.Element( XName.Get( "tcPr", DocX.w.NamespaceName ) );
  2619. if( tcPr == null )
  2620. {
  2621. Xml.SetElementValue( XName.Get( "tcPr", DocX.w.NamespaceName ), string.Empty );
  2622. tcPr = Xml.Element( XName.Get( "tcPr", DocX.w.NamespaceName ) );
  2623. }
  2624. /*
  2625. * Get the vAlign (table cell vertical alignment) element for this Cell,
  2626. * null will be return if no such element exists.
  2627. */
  2628. XElement vAlign = tcPr.Element( XName.Get( "vAlign", DocX.w.NamespaceName ) );
  2629. if( vAlign == null )
  2630. {
  2631. tcPr.SetElementValue( XName.Get( "vAlign", DocX.w.NamespaceName ), string.Empty );
  2632. vAlign = tcPr.Element( XName.Get( "vAlign", DocX.w.NamespaceName ) );
  2633. }
  2634. // Set the VerticalAlignment in 'val'
  2635. vAlign.SetAttributeValue( XName.Get( "val", DocX.w.NamespaceName ), value.ToString().ToLower() );
  2636. }
  2637. }
  2638. public Color Shading
  2639. {
  2640. get
  2641. {
  2642. /*
  2643. * Get the tcPr (table cell properties) element for this Cell,
  2644. * null will be return if no such element exists.
  2645. */
  2646. XElement tcPr = Xml.Element( XName.Get( "tcPr", DocX.w.NamespaceName ) );
  2647. // If tcPr is null, this cell contains no Color information.
  2648. // Get the shd (table shade) element for this Cell,
  2649. // null will be return if no such element exists.
  2650. XElement shd = tcPr?.Element( XName.Get( "shd", DocX.w.NamespaceName ) );
  2651. // If shd is null, this cell contains no Color information.
  2652. // Get the w attribute of the tcW element.
  2653. XAttribute fill = shd?.Attribute( XName.Get( "fill", DocX.w.NamespaceName ) );
  2654. // If fill is null, this cell contains no Color information.
  2655. if( fill == null )
  2656. return Color.White;
  2657. return ColorTranslator.FromHtml( string.Format( "#{0}", fill.Value ) );
  2658. }
  2659. set
  2660. {
  2661. /*
  2662. * Get the tcPr (table cell properties) element for this Cell,
  2663. * null will be return if no such element exists.
  2664. */
  2665. XElement tcPr = Xml.Element( XName.Get( "tcPr", DocX.w.NamespaceName ) );
  2666. if( tcPr == null )
  2667. {
  2668. Xml.SetElementValue( XName.Get( "tcPr", DocX.w.NamespaceName ), string.Empty );
  2669. tcPr = Xml.Element( XName.Get( "tcPr", DocX.w.NamespaceName ) );
  2670. }
  2671. /*
  2672. * Get the shd (table shade) element for this Cell,
  2673. * null will be return if no such element exists.
  2674. */
  2675. XElement shd = tcPr.Element( XName.Get( "shd", DocX.w.NamespaceName ) );
  2676. if( shd == null )
  2677. {
  2678. tcPr.SetElementValue( XName.Get( "shd", DocX.w.NamespaceName ), string.Empty );
  2679. shd = tcPr.Element( XName.Get( "shd", DocX.w.NamespaceName ) );
  2680. }
  2681. // The val attribute needs to be set to clear
  2682. shd.SetAttributeValue( XName.Get( "val", DocX.w.NamespaceName ), "clear" );
  2683. // The color attribute needs to be set to auto
  2684. shd.SetAttributeValue( XName.Get( "color", DocX.w.NamespaceName ), "auto" );
  2685. // The fill attribute needs to be set to the hex for this Color.
  2686. shd.SetAttributeValue( XName.Get( "fill", DocX.w.NamespaceName ), value.ToHex() );
  2687. }
  2688. }
  2689. /// <summary>
  2690. /// Width in pixels.
  2691. /// </summary>
  2692. public double Width
  2693. {
  2694. get
  2695. {
  2696. /*
  2697. * Get the tcPr (table cell properties) element for this Cell,
  2698. * null will be return if no such element exists.
  2699. */
  2700. XElement tcPr = Xml.Element( XName.Get( "tcPr", DocX.w.NamespaceName ) );
  2701. // If tcPr is null, this cell contains no width information.
  2702. // Get the tcW (table cell width) element for this Cell,
  2703. // null will be return if no such element exists.
  2704. XElement tcW = tcPr?.Element( XName.Get( "tcW", DocX.w.NamespaceName ) );
  2705. // If tcW is null, this cell contains no width information.
  2706. // Get the w attribute of the tcW element.
  2707. XAttribute w = tcW?.Attribute( XName.Get( "w", DocX.w.NamespaceName ) );
  2708. // If w is null, this cell contains no width information.
  2709. if( w == null )
  2710. return double.NaN;
  2711. // If w is not a double, something is wrong with this attributes value, so remove it and return double.NaN;
  2712. double widthInWordUnits;
  2713. if( !double.TryParse( w.Value, out widthInWordUnits ) )
  2714. {
  2715. w.Remove();
  2716. return double.NaN;
  2717. }
  2718. // Using 20 to match DocX._pageSizeMultiplier.
  2719. return ( widthInWordUnits / 20 );
  2720. }
  2721. set
  2722. {
  2723. /*
  2724. * Get the tcPr (table cell properties) element for this Cell,
  2725. * null will be return if no such element exists.
  2726. */
  2727. XElement tcPr = Xml.Element( XName.Get( "tcPr", DocX.w.NamespaceName ) );
  2728. if( tcPr == null )
  2729. {
  2730. Xml.SetElementValue( XName.Get( "tcPr", DocX.w.NamespaceName ), string.Empty );
  2731. tcPr = Xml.Element( XName.Get( "tcPr", DocX.w.NamespaceName ) );
  2732. }
  2733. /*
  2734. * Get the tcW (table cell width) element for this Cell,
  2735. * null will be return if no such element exists.
  2736. */
  2737. XElement tcW = tcPr.Element( XName.Get( "tcW", DocX.w.NamespaceName ) );
  2738. if( tcW == null )
  2739. {
  2740. tcPr.SetElementValue( XName.Get( "tcW", DocX.w.NamespaceName ), string.Empty );
  2741. tcW = tcPr.Element( XName.Get( "tcW", DocX.w.NamespaceName ) );
  2742. }
  2743. if( value == -1 )
  2744. {
  2745. // remove cell width; due to set on table prop.
  2746. tcW.Remove();
  2747. return;
  2748. }
  2749. // The type attribute needs to be set to dxa which represents "twips" or twentieths of a point. In other words, 1/1440th of an inch.
  2750. tcW.SetAttributeValue( XName.Get( "type", DocX.w.NamespaceName ), "dxa" );
  2751. // Using 20 to match DocX._pageSizeMultiplier.
  2752. tcW.SetAttributeValue( XName.Get( "w", DocX.w.NamespaceName ), ( value * 20 ).ToString() );
  2753. }
  2754. }
  2755. /// <summary>
  2756. /// LeftMargin in pixels.
  2757. /// </summary>
  2758. /// <example>
  2759. /// <code>
  2760. /// // Create a new document.
  2761. ///using (DocX document = DocX.Create("Test.docx"))
  2762. ///{
  2763. /// // Insert table into this document.
  2764. /// Table t = document.InsertTable(3, 3);
  2765. /// t.Design = TableDesign.TableGrid;
  2766. ///
  2767. /// // Get the center cell.
  2768. /// Cell center = t.Rows[1].Cells[1];
  2769. ///
  2770. /// // Insert some text so that we can see the effect of the Margins.
  2771. /// center.Paragraphs[0].Append("Center Cell");
  2772. ///
  2773. /// // Set the center cells Left, Margin to 10.
  2774. /// center.MarginLeft = 25;
  2775. ///
  2776. /// // Save the document.
  2777. /// document.Save();
  2778. ///}
  2779. /// </code>
  2780. /// </example>
  2781. public double MarginLeft
  2782. {
  2783. get
  2784. {
  2785. /*
  2786. * Get the tcPr (table cell properties) element for this Cell,
  2787. * null will be return if no such element exists.
  2788. */
  2789. XElement tcPr = Xml.Element( XName.Get( "tcPr", DocX.w.NamespaceName ) );
  2790. // If tcPr is null, this cell contains no width information.
  2791. if( tcPr == null )
  2792. return double.NaN;
  2793. /*
  2794. * Get the tcMar
  2795. *
  2796. */
  2797. XElement tcMar = tcPr.Element( XName.Get( "tcMar", DocX.w.NamespaceName ) );
  2798. // If tcMar is null, this cell contains no margin information.
  2799. // Get the left (LeftMargin) element
  2800. XElement tcMarLeft = tcMar?.Element( XName.Get( "left", DocX.w.NamespaceName ) );
  2801. // If tcMarLeft is null, this cell contains no left margin information.
  2802. // Get the w attribute of the tcMarLeft element.
  2803. XAttribute w = tcMarLeft?.Attribute( XName.Get( "w", DocX.w.NamespaceName ) );
  2804. // If w is null, this cell contains no width information.
  2805. if( w == null )
  2806. return double.NaN;
  2807. // If w is not a double, something is wrong with this attributes value, so remove it and return double.NaN;
  2808. double leftMarginInWordUnits;
  2809. if( !double.TryParse( w.Value, out leftMarginInWordUnits ) )
  2810. {
  2811. w.Remove();
  2812. return double.NaN;
  2813. }
  2814. // Using 20 to match DocX._pageSizeMultiplier.
  2815. return ( leftMarginInWordUnits / 20 );
  2816. }
  2817. set
  2818. {
  2819. /*
  2820. * Get the tcPr (table cell properties) element for this Cell,
  2821. * null will be return if no such element exists.
  2822. */
  2823. XElement tcPr = Xml.Element( XName.Get( "tcPr", DocX.w.NamespaceName ) );
  2824. if( tcPr == null )
  2825. {
  2826. Xml.SetElementValue( XName.Get( "tcPr", DocX.w.NamespaceName ), string.Empty );
  2827. tcPr = Xml.Element( XName.Get( "tcPr", DocX.w.NamespaceName ) );
  2828. }
  2829. /*
  2830. * Get the tcMar (table cell margin) element for this Cell,
  2831. * null will be return if no such element exists.
  2832. */
  2833. XElement tcMar = tcPr.Element( XName.Get( "tcMar", DocX.w.NamespaceName ) );
  2834. if( tcMar == null )
  2835. {
  2836. tcPr.SetElementValue( XName.Get( "tcMar", DocX.w.NamespaceName ), string.Empty );
  2837. tcMar = tcPr.Element( XName.Get( "tcMar", DocX.w.NamespaceName ) );
  2838. }
  2839. /*
  2840. * Get the left (table cell left margin) element for this Cell,
  2841. * null will be return if no such element exists.
  2842. */
  2843. XElement tcMarLeft = tcMar.Element( XName.Get( "left", DocX.w.NamespaceName ) );
  2844. if( tcMarLeft == null )
  2845. {
  2846. tcMar.SetElementValue( XName.Get( "left", DocX.w.NamespaceName ), string.Empty );
  2847. tcMarLeft = tcMar.Element( XName.Get( "left", DocX.w.NamespaceName ) );
  2848. }
  2849. // The type attribute needs to be set to dxa which represents "twips" or twentieths of a point. In other words, 1/1440th of an inch.
  2850. tcMarLeft.SetAttributeValue( XName.Get( "type", DocX.w.NamespaceName ), "dxa" );
  2851. // Using 20 to match DocX._pageSizeMultiplier.
  2852. tcMarLeft.SetAttributeValue( XName.Get( "w", DocX.w.NamespaceName ), ( value * 20 ).ToString() );
  2853. }
  2854. }
  2855. /// <summary>
  2856. /// RightMargin in pixels.
  2857. /// </summary>
  2858. /// <example>
  2859. /// <code>
  2860. /// // Create a new document.
  2861. ///using (DocX document = DocX.Create("Test.docx"))
  2862. ///{
  2863. /// // Insert table into this document.
  2864. /// Table t = document.InsertTable(3, 3);
  2865. /// t.Design = TableDesign.TableGrid;
  2866. ///
  2867. /// // Get the center cell.
  2868. /// Cell center = t.Rows[1].Cells[1];
  2869. ///
  2870. /// // Insert some text so that we can see the effect of the Margins.
  2871. /// center.Paragraphs[0].Append("Center Cell");
  2872. ///
  2873. /// // Set the center cells Right, Margin to 10.
  2874. /// center.MarginRight = 25;
  2875. ///
  2876. /// // Save the document.
  2877. /// document.Save();
  2878. ///}
  2879. /// </code>
  2880. /// </example>
  2881. public double MarginRight
  2882. {
  2883. get
  2884. {
  2885. /*
  2886. * Get the tcPr (table cell properties) element for this Cell,
  2887. * null will be return if no such element exists.
  2888. */
  2889. XElement tcPr = Xml.Element( XName.Get( "tcPr", DocX.w.NamespaceName ) );
  2890. // If tcPr is null, this cell contains no width information.
  2891. if( tcPr == null )
  2892. return double.NaN;
  2893. /*
  2894. * Get the tcMar
  2895. *
  2896. */
  2897. XElement tcMar = tcPr.Element( XName.Get( "tcMar", DocX.w.NamespaceName ) );
  2898. // If tcMar is null, this cell contains no margin information.
  2899. // Get the right (RightMargin) element
  2900. XElement tcMarRight = tcMar?.Element( XName.Get( "right", DocX.w.NamespaceName ) );
  2901. // If tcMarRight is null, this cell contains no right margin information.
  2902. // Get the w attribute of the tcMarRight element.
  2903. XAttribute w = tcMarRight?.Attribute( XName.Get( "w", DocX.w.NamespaceName ) );
  2904. // If w is null, this cell contains no width information.
  2905. if( w == null )
  2906. return double.NaN;
  2907. // If w is not a double, something is wrong with this attributes value, so remove it and return double.NaN;
  2908. double rightMarginInWordUnits;
  2909. if( !double.TryParse( w.Value, out rightMarginInWordUnits ) )
  2910. {
  2911. w.Remove();
  2912. return double.NaN;
  2913. }
  2914. // Using 20 to match DocX._pageSizeMultiplier.
  2915. return ( rightMarginInWordUnits / 20 );
  2916. }
  2917. set
  2918. {
  2919. /*
  2920. * Get the tcPr (table cell properties) element for this Cell,
  2921. * null will be return if no such element exists.
  2922. */
  2923. XElement tcPr = Xml.Element( XName.Get( "tcPr", DocX.w.NamespaceName ) );
  2924. if( tcPr == null )
  2925. {
  2926. Xml.SetElementValue( XName.Get( "tcPr", DocX.w.NamespaceName ), string.Empty );
  2927. tcPr = Xml.Element( XName.Get( "tcPr", DocX.w.NamespaceName ) );
  2928. }
  2929. /*
  2930. * Get the tcMar (table cell margin) element for this Cell,
  2931. * null will be return if no such element exists.
  2932. */
  2933. XElement tcMar = tcPr.Element( XName.Get( "tcMar", DocX.w.NamespaceName ) );
  2934. if( tcMar == null )
  2935. {
  2936. tcPr.SetElementValue( XName.Get( "tcMar", DocX.w.NamespaceName ), string.Empty );
  2937. tcMar = tcPr.Element( XName.Get( "tcMar", DocX.w.NamespaceName ) );
  2938. }
  2939. /*
  2940. * Get the right (table cell right margin) element for this Cell,
  2941. * null will be return if no such element exists.
  2942. */
  2943. XElement tcMarRight = tcMar.Element( XName.Get( "right", DocX.w.NamespaceName ) );
  2944. if( tcMarRight == null )
  2945. {
  2946. tcMar.SetElementValue( XName.Get( "right", DocX.w.NamespaceName ), string.Empty );
  2947. tcMarRight = tcMar.Element( XName.Get( "right", DocX.w.NamespaceName ) );
  2948. }
  2949. // The type attribute needs to be set to dxa which represents "twips" or twentieths of a point. In other words, 1/1440th of an inch.
  2950. tcMarRight.SetAttributeValue( XName.Get( "type", DocX.w.NamespaceName ), "dxa" );
  2951. // Using 20 to match DocX._pageSizeMultiplier.
  2952. tcMarRight.SetAttributeValue( XName.Get( "w", DocX.w.NamespaceName ), ( value * 20 ).ToString() );
  2953. }
  2954. }
  2955. /// <summary>
  2956. /// TopMargin in pixels.
  2957. /// </summary>
  2958. /// <example>
  2959. /// <code>
  2960. /// // Create a new document.
  2961. ///using (DocX document = DocX.Create("Test.docx"))
  2962. ///{
  2963. /// // Insert table into this document.
  2964. /// Table t = document.InsertTable(3, 3);
  2965. /// t.Design = TableDesign.TableGrid;
  2966. ///
  2967. /// // Get the center cell.
  2968. /// Cell center = t.Rows[1].Cells[1];
  2969. ///
  2970. /// // Insert some text so that we can see the effect of the Margins.
  2971. /// center.Paragraphs[0].Append("Center Cell");
  2972. ///
  2973. /// // Set the center cells Top, Margin to 10.
  2974. /// center.MarginTop = 25;
  2975. ///
  2976. /// // Save the document.
  2977. /// document.Save();
  2978. ///}
  2979. /// </code>
  2980. /// </example>
  2981. public double MarginTop
  2982. {
  2983. get
  2984. {
  2985. /*
  2986. * Get the tcPr (table cell properties) element for this Cell,
  2987. * null will be return if no such element exists.
  2988. */
  2989. XElement tcPr = Xml.Element( XName.Get( "tcPr", DocX.w.NamespaceName ) );
  2990. // If tcPr is null, this cell contains no width information.
  2991. if( tcPr == null )
  2992. return double.NaN;
  2993. /*
  2994. * Get the tcMar
  2995. *
  2996. */
  2997. XElement tcMar = tcPr.Element( XName.Get( "tcMar", DocX.w.NamespaceName ) );
  2998. // If tcMar is null, this cell contains no margin information.
  2999. // Get the top (TopMargin) element
  3000. XElement tcMarTop = tcMar?.Element( XName.Get( "top", DocX.w.NamespaceName ) );
  3001. // If tcMarTop is null, this cell contains no top margin information.
  3002. // Get the w attribute of the tcMarTop element.
  3003. XAttribute w = tcMarTop?.Attribute( XName.Get( "w", DocX.w.NamespaceName ) );
  3004. // If w is null, this cell contains no width information.
  3005. if( w == null )
  3006. return double.NaN;
  3007. // If w is not a double, something is wrong with this attributes value, so remove it and return double.NaN;
  3008. double topMarginInWordUnits;
  3009. if( !double.TryParse( w.Value, out topMarginInWordUnits ) )
  3010. {
  3011. w.Remove();
  3012. return double.NaN;
  3013. }
  3014. // Using 20 to match DocX._pageSizeMultiplier.
  3015. return ( topMarginInWordUnits / 20 );
  3016. }
  3017. set
  3018. {
  3019. /*
  3020. * Get the tcPr (table cell properties) element for this Cell,
  3021. * null will be return if no such element exists.
  3022. */
  3023. XElement tcPr = Xml.Element( XName.Get( "tcPr", DocX.w.NamespaceName ) );
  3024. if( tcPr == null )
  3025. {
  3026. Xml.SetElementValue( XName.Get( "tcPr", DocX.w.NamespaceName ), string.Empty );
  3027. tcPr = Xml.Element( XName.Get( "tcPr", DocX.w.NamespaceName ) );
  3028. }
  3029. /*
  3030. * Get the tcMar (table cell margin) element for this Cell,
  3031. * null will be return if no such element exists.
  3032. */
  3033. XElement tcMar = tcPr.Element( XName.Get( "tcMar", DocX.w.NamespaceName ) );
  3034. if( tcMar == null )
  3035. {
  3036. tcPr.SetElementValue( XName.Get( "tcMar", DocX.w.NamespaceName ), string.Empty );
  3037. tcMar = tcPr.Element( XName.Get( "tcMar", DocX.w.NamespaceName ) );
  3038. }
  3039. /*
  3040. * Get the top (table cell top margin) element for this Cell,
  3041. * null will be return if no such element exists.
  3042. */
  3043. XElement tcMarTop = tcMar.Element( XName.Get( "top", DocX.w.NamespaceName ) );
  3044. if( tcMarTop == null )
  3045. {
  3046. tcMar.SetElementValue( XName.Get( "top", DocX.w.NamespaceName ), string.Empty );
  3047. tcMarTop = tcMar.Element( XName.Get( "top", DocX.w.NamespaceName ) );
  3048. }
  3049. // The type attribute needs to be set to dxa which represents "twips" or twentieths of a point. In other words, 1/1440th of an inch.
  3050. tcMarTop.SetAttributeValue( XName.Get( "type", DocX.w.NamespaceName ), "dxa" );
  3051. // Using 20 to match DocX._pageSizeMultiplier.
  3052. tcMarTop.SetAttributeValue( XName.Get( "w", DocX.w.NamespaceName ), ( value * 20 ).ToString() );
  3053. }
  3054. }
  3055. /// <summary>
  3056. /// BottomMargin in pixels.
  3057. /// </summary>
  3058. /// <example>
  3059. /// <code>
  3060. /// // Create a new document.
  3061. ///using (DocX document = DocX.Create("Test.docx"))
  3062. ///{
  3063. /// // Insert table into this document.
  3064. /// Table t = document.InsertTable(3, 3);
  3065. /// t.Design = TableDesign.TableGrid;
  3066. ///
  3067. /// // Get the center cell.
  3068. /// Cell center = t.Rows[1].Cells[1];
  3069. ///
  3070. /// // Insert some text so that we can see the effect of the Margins.
  3071. /// center.Paragraphs[0].Append("Center Cell");
  3072. ///
  3073. /// // Set the center cells Top, Margin to 10.
  3074. /// center.MarginBottom = 25;
  3075. ///
  3076. /// // Save the document.
  3077. /// document.Save();
  3078. ///}
  3079. /// </code>
  3080. /// </example>
  3081. public double MarginBottom
  3082. {
  3083. get
  3084. {
  3085. /*
  3086. * Get the tcPr (table cell properties) element for this Cell,
  3087. * null will be return if no such element exists.
  3088. */
  3089. XElement tcPr = Xml.Element( XName.Get( "tcPr", DocX.w.NamespaceName ) );
  3090. // If tcPr is null, this cell contains no width information.
  3091. if( tcPr == null )
  3092. return double.NaN;
  3093. /*
  3094. * Get the tcMar
  3095. *
  3096. */
  3097. XElement tcMar = tcPr.Element( XName.Get( "tcMar", DocX.w.NamespaceName ) );
  3098. // If tcMar is null, this cell contains no margin information.
  3099. // Get the bottom (BottomMargin) element
  3100. XElement tcMarBottom = tcMar?.Element( XName.Get( "bottom", DocX.w.NamespaceName ) );
  3101. // If tcMarBottom is null, this cell contains no bottom margin information.
  3102. // Get the w attribute of the tcMarBottom element.
  3103. XAttribute w = tcMarBottom?.Attribute( XName.Get( "w", DocX.w.NamespaceName ) );
  3104. // If w is null, this cell contains no width information.
  3105. if( w == null )
  3106. return double.NaN;
  3107. // If w is not a double, something is wrong with this attributes value, so remove it and return double.NaN;
  3108. double bottomMarginInWordUnits;
  3109. if( !double.TryParse( w.Value, out bottomMarginInWordUnits ) )
  3110. {
  3111. w.Remove();
  3112. return double.NaN;
  3113. }
  3114. // Using 20 to match DocX._pageSizeMultiplier.
  3115. return ( bottomMarginInWordUnits / 20 );
  3116. }
  3117. set
  3118. {
  3119. /*
  3120. * Get the tcPr (table cell properties) element for this Cell,
  3121. * null will be return if no such element exists.
  3122. */
  3123. XElement tcPr = Xml.Element( XName.Get( "tcPr", DocX.w.NamespaceName ) );
  3124. if( tcPr == null )
  3125. {
  3126. Xml.SetElementValue( XName.Get( "tcPr", DocX.w.NamespaceName ), string.Empty );
  3127. tcPr = Xml.Element( XName.Get( "tcPr", DocX.w.NamespaceName ) );
  3128. }
  3129. /*
  3130. * Get the tcMar (table cell margin) element for this Cell,
  3131. * null will be return if no such element exists.
  3132. */
  3133. XElement tcMar = tcPr.Element( XName.Get( "tcMar", DocX.w.NamespaceName ) );
  3134. if( tcMar == null )
  3135. {
  3136. tcPr.SetElementValue( XName.Get( "tcMar", DocX.w.NamespaceName ), string.Empty );
  3137. tcMar = tcPr.Element( XName.Get( "tcMar", DocX.w.NamespaceName ) );
  3138. }
  3139. /*
  3140. * Get the bottom (table cell bottom margin) element for this Cell,
  3141. * null will be return if no such element exists.
  3142. */
  3143. XElement tcMarBottom = tcMar.Element( XName.Get( "bottom", DocX.w.NamespaceName ) );
  3144. if( tcMarBottom == null )
  3145. {
  3146. tcMar.SetElementValue( XName.Get( "bottom", DocX.w.NamespaceName ), string.Empty );
  3147. tcMarBottom = tcMar.Element( XName.Get( "bottom", DocX.w.NamespaceName ) );
  3148. }
  3149. // The type attribute needs to be set to dxa which represents "twips" or twentieths of a point. In other words, 1/1440th of an inch.
  3150. tcMarBottom.SetAttributeValue( XName.Get( "type", DocX.w.NamespaceName ), "dxa" );
  3151. // Using 20 to match DocX._pageSizeMultiplier.
  3152. tcMarBottom.SetAttributeValue( XName.Get( "w", DocX.w.NamespaceName ), ( value * 20 ).ToString() );
  3153. }
  3154. }
  3155. public Color FillColor
  3156. {
  3157. get
  3158. {
  3159. /*
  3160. * Get the tcPr (table cell properties) element for this Cell,
  3161. * null will be return if no such element exists.
  3162. */
  3163. XElement tcPr = Xml.Element( XName.Get( "tcPr", DocX.w.NamespaceName ) );
  3164. XElement shd = tcPr?.Element( XName.Get( "shd", DocX.w.NamespaceName ) );
  3165. XAttribute fill = shd?.Attribute( XName.Get( "fill", DocX.w.NamespaceName ) );
  3166. if( fill == null )
  3167. return Color.Empty;
  3168. int argb = Int32.Parse( fill.Value.Replace( "#", "" ), NumberStyles.HexNumber );
  3169. return Color.FromArgb( argb );
  3170. }
  3171. set
  3172. {
  3173. /*
  3174. * Get the tcPr (table cell properties) element for this Cell,
  3175. * null will be return if no such element exists.
  3176. */
  3177. XElement tcPr = Xml.Element( XName.Get( "tcPr", DocX.w.NamespaceName ) );
  3178. if( tcPr == null )
  3179. {
  3180. Xml.SetElementValue( XName.Get( "tcPr", DocX.w.NamespaceName ), string.Empty );
  3181. tcPr = Xml.Element( XName.Get( "tcPr", DocX.w.NamespaceName ) );
  3182. }
  3183. /*
  3184. * Get the tcW (table cell width) element for this Cell,
  3185. * null will be return if no such element exists.
  3186. */
  3187. XElement shd = tcPr.Element( XName.Get( "shd", DocX.w.NamespaceName ) );
  3188. if( shd == null )
  3189. {
  3190. tcPr.SetElementValue( XName.Get( "shd", DocX.w.NamespaceName ), string.Empty );
  3191. shd = tcPr.Element( XName.Get( "shd", DocX.w.NamespaceName ) );
  3192. }
  3193. shd.SetAttributeValue( XName.Get( "val", DocX.w.NamespaceName ), "clear" );
  3194. shd.SetAttributeValue( XName.Get( "color", DocX.w.NamespaceName ), "auto" );
  3195. shd.SetAttributeValue( XName.Get( "fill", DocX.w.NamespaceName ), value.ToHex() );
  3196. }
  3197. }
  3198. public TextDirection TextDirection
  3199. {
  3200. get
  3201. {
  3202. var tcPr = Xml.Element( XName.Get( "tcPr", DocX.w.NamespaceName ) );
  3203. var textDirection = tcPr?.Element( XName.Get( "textDirection", DocX.w.NamespaceName ) );
  3204. var val = textDirection?.Attribute( XName.Get( "val", DocX.w.NamespaceName ) );
  3205. if( val != null )
  3206. {
  3207. TextDirection textDirectionValue;
  3208. var success = Enum.TryParse( val.Value, out textDirectionValue );
  3209. if( success )
  3210. return textDirectionValue;
  3211. else
  3212. {
  3213. val.Remove();
  3214. }
  3215. }
  3216. return TextDirection.right;
  3217. }
  3218. set
  3219. {
  3220. var tcPrXName = XName.Get( "tcPr", DocX.w.NamespaceName );
  3221. var textDirectionXName = XName.Get( "textDirection", DocX.w.NamespaceName );
  3222. var tcPr = Xml.Element( tcPrXName );
  3223. if( tcPr == null )
  3224. {
  3225. Xml.SetElementValue( tcPrXName, string.Empty );
  3226. tcPr = Xml.Element( tcPrXName );
  3227. }
  3228. var textDirection = tcPr.Element( textDirectionXName );
  3229. if( textDirection == null )
  3230. {
  3231. tcPr.SetElementValue( textDirectionXName, string.Empty );
  3232. textDirection = tcPr.Element( textDirectionXName );
  3233. }
  3234. textDirection.SetAttributeValue( XName.Get( "val", DocX.w.NamespaceName ), value.ToString() );
  3235. }
  3236. }
  3237. /// <summary>
  3238. /// Returns the Cell.GridSpan => How many cells are merged.
  3239. /// </summary>
  3240. public int GridSpan
  3241. {
  3242. get
  3243. {
  3244. int gridSpanValue = 0;
  3245. var tcPr = Xml.Element( XName.Get( "tcPr", DocX.w.NamespaceName ) );
  3246. var gridSpan = tcPr?.Element( XName.Get( "gridSpan", DocX.w.NamespaceName ) );
  3247. if( gridSpan != null )
  3248. {
  3249. var gridSpanAttrValue = gridSpan.Attribute( XName.Get( "val", DocX.w.NamespaceName ) );
  3250. int value;
  3251. if( gridSpanAttrValue != null && int.TryParse( gridSpanAttrValue.Value, out value ) )
  3252. gridSpanValue = value;
  3253. }
  3254. return gridSpanValue;
  3255. }
  3256. }
  3257. #endregion
  3258. #region Constructors
  3259. internal Cell( Row row, DocX document, XElement xml )
  3260. : base( document, xml )
  3261. {
  3262. _row = row;
  3263. this.PackagePart = row.PackagePart;
  3264. }
  3265. #endregion
  3266. #region Public Methods
  3267. /// <summary>
  3268. /// Set the table cell border
  3269. /// </summary>
  3270. /// <example>
  3271. /// <code>
  3272. ///// Create a new document.
  3273. ///using (DocX document = DocX.Create("Test.docx"))
  3274. ///{
  3275. /// // Insert a table into this document.
  3276. /// Table t = document.InsertTable(3, 3);
  3277. ///
  3278. /// // Get the center cell.
  3279. /// Cell center = t.Rows[1].Cells[1];
  3280. ///
  3281. /// // Create a large blue border.
  3282. /// Border b = new Border(BorderStyle.Tcbs_single, BorderSize.seven, 0, Color.Blue);
  3283. ///
  3284. /// // Set the center cells Top, Bottom, Left and Right Borders to b.
  3285. /// center.SetBorder(TableCellBorderType.Top, b);
  3286. /// center.SetBorder(TableCellBorderType.Bottom, b);
  3287. /// center.SetBorder(TableCellBorderType.Left, b);
  3288. /// center.SetBorder(TableCellBorderType.Right, b);
  3289. ///
  3290. /// // Save the document.
  3291. /// document.Save();
  3292. ///}
  3293. /// </code>
  3294. /// </example>
  3295. /// <param name="borderType">Table Cell border to set</param>
  3296. /// <param name="border">Border object to set the table cell border</param>
  3297. public void SetBorder( TableCellBorderType borderType, Border border )
  3298. {
  3299. /*
  3300. * Get the tcPr (table cell properties) element for this Cell,
  3301. * null will be return if no such element exists.
  3302. */
  3303. XElement tcPr = Xml.Element( XName.Get( "tcPr", DocX.w.NamespaceName ) );
  3304. if( tcPr == null )
  3305. {
  3306. Xml.SetElementValue( XName.Get( "tcPr", DocX.w.NamespaceName ), string.Empty );
  3307. tcPr = Xml.Element( XName.Get( "tcPr", DocX.w.NamespaceName ) );
  3308. }
  3309. /*
  3310. * Get the tblBorders (table cell borders) element for this Cell,
  3311. * null will be return if no such element exists.
  3312. */
  3313. XElement tcBorders = tcPr.Element( XName.Get( "tcBorders", DocX.w.NamespaceName ) );
  3314. if( tcBorders == null )
  3315. {
  3316. tcPr.SetElementValue( XName.Get( "tcBorders", DocX.w.NamespaceName ), string.Empty );
  3317. tcBorders = tcPr.Element( XName.Get( "tcBorders", DocX.w.NamespaceName ) );
  3318. }
  3319. /*
  3320. * Get the 'borderType' (table cell border) element for this Cell,
  3321. * null will be return if no such element exists.
  3322. */
  3323. var tcbordertype = borderType.ToString();
  3324. switch( borderType )
  3325. {
  3326. case TableCellBorderType.TopLeftToBottomRight:
  3327. tcbordertype = "tl2br";
  3328. break;
  3329. case TableCellBorderType.TopRightToBottomLeft:
  3330. tcbordertype = "tr2bl";
  3331. break;
  3332. default:
  3333. // only lower the first char of string (because of insideH and insideV)
  3334. tcbordertype = tcbordertype.Substring( 0, 1 ).ToLower() + tcbordertype.Substring( 1 );
  3335. break;
  3336. }
  3337. XElement tcBorderType = tcBorders.Element( XName.Get( borderType.ToString(), DocX.w.NamespaceName ) );
  3338. if( tcBorderType == null )
  3339. {
  3340. tcBorders.SetElementValue( XName.Get( tcbordertype, DocX.w.NamespaceName ), string.Empty );
  3341. tcBorderType = tcBorders.Element( XName.Get( tcbordertype, DocX.w.NamespaceName ) );
  3342. }
  3343. // get string value of border style
  3344. string borderstyle = border.Tcbs.ToString().Substring( 5 );
  3345. borderstyle = borderstyle.Substring( 0, 1 ).ToLower() + borderstyle.Substring( 1 );
  3346. // The val attribute is used for the border style
  3347. tcBorderType.SetAttributeValue( XName.Get( "val", DocX.w.NamespaceName ), borderstyle );
  3348. int size;
  3349. switch( border.Size )
  3350. {
  3351. case BorderSize.one:
  3352. size = 2;
  3353. break;
  3354. case BorderSize.two:
  3355. size = 4;
  3356. break;
  3357. case BorderSize.three:
  3358. size = 6;
  3359. break;
  3360. case BorderSize.four:
  3361. size = 8;
  3362. break;
  3363. case BorderSize.five:
  3364. size = 12;
  3365. break;
  3366. case BorderSize.six:
  3367. size = 18;
  3368. break;
  3369. case BorderSize.seven:
  3370. size = 24;
  3371. break;
  3372. case BorderSize.eight:
  3373. size = 36;
  3374. break;
  3375. case BorderSize.nine:
  3376. size = 48;
  3377. break;
  3378. default:
  3379. size = 2;
  3380. break;
  3381. }
  3382. // The sz attribute is used for the border size
  3383. tcBorderType.SetAttributeValue( XName.Get( "sz", DocX.w.NamespaceName ), ( size ).ToString() );
  3384. // The space attribute is used for the cell spacing (probably '0')
  3385. tcBorderType.SetAttributeValue( XName.Get( "space", DocX.w.NamespaceName ), ( border.Space ).ToString() );
  3386. // The color attribute is used for the border color
  3387. tcBorderType.SetAttributeValue( XName.Get( "color", DocX.w.NamespaceName ), border.Color.ToHex() );
  3388. }
  3389. /// <summary>
  3390. /// Get a table cell border
  3391. /// </summary>
  3392. /// <param name="borderType">The table cell border to get</param>
  3393. public Border GetBorder( TableCellBorderType borderType )
  3394. {
  3395. // instance with default border values
  3396. var b = new Border();
  3397. /*
  3398. * Get the tcPr (table cell properties) element for this Cell,
  3399. * null will be return if no such element exists.
  3400. */
  3401. XElement tcPr = Xml.Element( XName.Get( "tcPr", DocX.w.NamespaceName ) );
  3402. if( tcPr == null )
  3403. {
  3404. // uses default border style
  3405. }
  3406. /*
  3407. * Get the tcBorders (table cell borders) element for this Cell,
  3408. * null will be return if no such element exists.
  3409. */
  3410. XElement tcBorders = tcPr.Element( XName.Get( "tcBorders", DocX.w.NamespaceName ) );
  3411. if( tcBorders == null )
  3412. {
  3413. // uses default border style
  3414. }
  3415. /*
  3416. * Get the 'borderType' (cell border) element for this Cell,
  3417. * null will be return if no such element exists.
  3418. */
  3419. var tcbordertype = borderType.ToString();
  3420. switch( tcbordertype )
  3421. {
  3422. case "TopLeftToBottomRight":
  3423. tcbordertype = "tl2br";
  3424. break;
  3425. case "TopRightToBottomLeft":
  3426. tcbordertype = "tr2bl";
  3427. break;
  3428. default:
  3429. // only lower the first char of string (because of insideH and insideV)
  3430. tcbordertype = tcbordertype.Substring( 0, 1 ).ToLower() + tcbordertype.Substring( 1 );
  3431. break;
  3432. }
  3433. XElement tcBorderType = tcBorders.Element( XName.Get( tcbordertype, DocX.w.NamespaceName ) );
  3434. if( tcBorderType == null )
  3435. {
  3436. // uses default border style
  3437. }
  3438. // The val attribute is used for the border style
  3439. XAttribute val = tcBorderType.Attribute( XName.Get( "val", DocX.w.NamespaceName ) );
  3440. // If val is null, this cell contains no border information.
  3441. if( val == null )
  3442. {
  3443. // uses default border style
  3444. }
  3445. else
  3446. {
  3447. try
  3448. {
  3449. string bordertype = "Tcbs_" + val.Value;
  3450. b.Tcbs = ( BorderStyle )Enum.Parse( typeof( BorderStyle ), bordertype );
  3451. }
  3452. catch
  3453. {
  3454. val.Remove();
  3455. // uses default border style
  3456. }
  3457. }
  3458. // The sz attribute is used for the border size
  3459. XAttribute sz = tcBorderType.Attribute( XName.Get( "sz", DocX.w.NamespaceName ) );
  3460. // If sz is null, this border contains no size information.
  3461. if( sz == null )
  3462. {
  3463. // uses default border style
  3464. }
  3465. else
  3466. {
  3467. // If sz is not an int, something is wrong with this attributes value, so remove it
  3468. int numerical_size;
  3469. if( !int.TryParse( sz.Value, out numerical_size ) )
  3470. sz.Remove();
  3471. else
  3472. {
  3473. switch( numerical_size )
  3474. {
  3475. case 2:
  3476. b.Size = BorderSize.one;
  3477. break;
  3478. case 4:
  3479. b.Size = BorderSize.two;
  3480. break;
  3481. case 6:
  3482. b.Size = BorderSize.three;
  3483. break;
  3484. case 8:
  3485. b.Size = BorderSize.four;
  3486. break;
  3487. case 12:
  3488. b.Size = BorderSize.five;
  3489. break;
  3490. case 18:
  3491. b.Size = BorderSize.six;
  3492. break;
  3493. case 24:
  3494. b.Size = BorderSize.seven;
  3495. break;
  3496. case 36:
  3497. b.Size = BorderSize.eight;
  3498. break;
  3499. case 48:
  3500. b.Size = BorderSize.nine;
  3501. break;
  3502. default:
  3503. b.Size = BorderSize.one;
  3504. break;
  3505. }
  3506. }
  3507. }
  3508. // The space attribute is used for the border spacing (probably '0')
  3509. XAttribute space = tcBorderType.Attribute( XName.Get( "space", DocX.w.NamespaceName ) );
  3510. // If space is null, this border contains no space information.
  3511. if( space == null )
  3512. {
  3513. // uses default border style
  3514. }
  3515. else
  3516. {
  3517. // If space is not an int, something is wrong with this attributes value, so remove it
  3518. int borderspace;
  3519. if( !int.TryParse( space.Value, out borderspace ) )
  3520. {
  3521. space.Remove();
  3522. // uses default border style
  3523. }
  3524. else
  3525. {
  3526. b.Space = borderspace;
  3527. }
  3528. }
  3529. // The color attribute is used for the border color
  3530. XAttribute color = tcBorderType.Attribute( XName.Get( "color", DocX.w.NamespaceName ) );
  3531. if( color == null )
  3532. {
  3533. // uses default border style
  3534. }
  3535. else
  3536. {
  3537. // If color is not a Color, something is wrong with this attributes value, so remove it
  3538. try
  3539. {
  3540. b.Color = ColorTranslator.FromHtml( string.Format( "#{0}", color.Value ) );
  3541. }
  3542. catch
  3543. {
  3544. color.Remove();
  3545. // uses default border style
  3546. }
  3547. }
  3548. return b;
  3549. }
  3550. public override Table InsertTable( int rowCount, int columnCount )
  3551. {
  3552. var table = base.InsertTable( rowCount, columnCount );
  3553. table.PackagePart = this.PackagePart;
  3554. this.InsertParagraph(); //It is necessary to put paragraph in the end of the cell, without it MS-Word will say that the document is corrupted
  3555. //IMPORTANT: It will be better to check all methods that work with adding anything to cells
  3556. return table;
  3557. }
  3558. #endregion
  3559. /// <summary>
  3560. /// Gets or Sets the fill color of this Cell.
  3561. /// </summary>
  3562. /// <example>
  3563. /// <code>
  3564. /// // Create a new document.
  3565. /// using (DocX document = DocX.Create("Test.docx"))
  3566. /// {
  3567. /// // Insert a table into this document.
  3568. /// Table t = document.InsertTable(3, 3);
  3569. ///
  3570. /// // Fill the first cell as Blue.
  3571. /// t.Rows[0].Cells[0].FillColor = Color.Blue;
  3572. /// // Fill the middle cell as Red.
  3573. /// t.Rows[1].Cells[1].FillColor = Color.Red;
  3574. /// // Fill the last cell as Green.
  3575. /// t.Rows[2].Cells[2].FillColor = Color.Green;
  3576. ///
  3577. /// // Save the document.
  3578. /// document.Save();
  3579. /// }
  3580. /// </code>
  3581. /// </example>
  3582. }
  3583. public class TableLook
  3584. {
  3585. #region Public Properties
  3586. public bool FirstRow
  3587. {
  3588. get;
  3589. set;
  3590. }
  3591. public bool LastRow
  3592. {
  3593. get;
  3594. set;
  3595. }
  3596. public bool FirstColumn
  3597. {
  3598. get;
  3599. set;
  3600. }
  3601. public bool LastColumn
  3602. {
  3603. get;
  3604. set;
  3605. }
  3606. public bool NoHorizontalBanding
  3607. {
  3608. get;
  3609. set;
  3610. }
  3611. public bool NoVerticalBanding
  3612. {
  3613. get;
  3614. set;
  3615. }
  3616. #endregion
  3617. #region Constructors
  3618. public TableLook()
  3619. {
  3620. }
  3621. public TableLook( bool firstRow, bool lastRow, bool firstColumn, bool lastColumn, bool noHorizontalBanding, bool noVerticalBanding )
  3622. {
  3623. this.FirstRow = firstRow;
  3624. this.LastRow = lastRow;
  3625. this.FirstColumn = firstColumn;
  3626. this.LastColumn = lastColumn;
  3627. this.NoHorizontalBanding = noHorizontalBanding;
  3628. this.NoVerticalBanding = noVerticalBanding;
  3629. }
  3630. #endregion
  3631. }
  3632. }