您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

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