| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Xml.Linq;
- using System.IO.Packaging;
- using System.IO;
- using System.Drawing;
- using System.Globalization;
- using System.Collections.ObjectModel;
-
- namespace Novacode
- {
- /// <summary>
- /// Represents a Table in a document.
- /// </summary>
- public class Table : InsertBeforeOrAfter
- {
- private Alignment alignment;
- private AutoFit autofit;
- private float[] ColumnWidthsValue;
- /// <summary>
- /// Merge cells in given column starting with startRow and ending with endRow.
- /// </summary>
- /// <remarks>
- /// Added by arudoy patch: 11608
- /// </remarks>
- public void MergeCellsInColumn(int columnIndex, int startRow, int endRow)
- {
- // Check for valid start and end indexes.
- if (columnIndex < 0 || columnIndex >= ColumnCount)
- throw new IndexOutOfRangeException();
-
- if (startRow < 0 || endRow <= startRow || endRow >= Rows.Count)
- throw new IndexOutOfRangeException();
- // Foreach each Cell between startIndex and endIndex inclusive.
- foreach (Row row in Rows.Where((z, i) => i > startRow && i <= endRow))
- {
- Cell c = row.Cells[columnIndex];
- XElement tcPr = c.Xml.Element(XName.Get("tcPr", DocX.w.NamespaceName));
- if (tcPr == null)
- {
- c.Xml.SetElementValue(XName.Get("tcPr", DocX.w.NamespaceName), string.Empty);
- tcPr = c.Xml.Element(XName.Get("tcPr", DocX.w.NamespaceName));
- }
-
- XElement vMerge = tcPr.Element(XName.Get("vMerge", DocX.w.NamespaceName));
- if (vMerge == null)
- {
- tcPr.SetElementValue(XName.Get("vMerge", DocX.w.NamespaceName), string.Empty);
- vMerge = tcPr.Element(XName.Get("vMerge", DocX.w.NamespaceName));
- }
- }
-
- /*
- * Get the tcPr (table cell properties) element for the first cell in this merge,
- * null will be returned if no such element exists.
- */
- XElement start_tcPr;
- if (columnIndex > Rows[startRow].Cells.Count)
- start_tcPr = Rows[startRow].Cells[Rows[startRow].Cells.Count - 1].Xml.Element(XName.Get("tcPr", DocX.w.NamespaceName));
- else
- start_tcPr = Rows[startRow].Cells[columnIndex].Xml.Element(XName.Get("tcPr", DocX.w.NamespaceName));
- if (start_tcPr == null)
- {
- Rows[startRow].Cells[columnIndex].Xml.SetElementValue(XName.Get("tcPr", DocX.w.NamespaceName), string.Empty);
- start_tcPr = Rows[startRow].Cells[columnIndex].Xml.Element(XName.Get("tcPr", DocX.w.NamespaceName));
- }
-
- /*
- * Get the gridSpan element of this row,
- * null will be returned if no such element exists.
- */
- XElement start_vMerge = start_tcPr.Element(XName.Get("vMerge", DocX.w.NamespaceName));
- if (start_vMerge == null)
- {
- start_tcPr.SetElementValue(XName.Get("vMerge", DocX.w.NamespaceName), string.Empty);
- start_vMerge = start_tcPr.Element(XName.Get("vMerge", DocX.w.NamespaceName));
- }
-
- start_vMerge.SetAttributeValue(XName.Get("val", DocX.w.NamespaceName), "restart");
- }
-
- /// <summary>
- /// Returns a list of all Paragraphs inside this container.
- /// </summary>
- ///
- public virtual List<Paragraph> Paragraphs
- {
- get
- {
- var paragraphs = new List<Paragraph>();
-
- foreach (Row r in Rows)
- paragraphs.AddRange(r.Paragraphs);
-
- return paragraphs;
- }
- }
-
- /// <summary>
- /// Returns a list of all Pictures in a Table.
- /// </summary>
- /// <example>
- /// Returns a list of all Pictures in a Table.
- /// <code>
- /// <![CDATA[
- /// // Create a document.
- /// using (DocX document = DocX.Load(@"Test.docx"))
- /// {
- /// // Get the first Table in a document.
- /// Table t = document.Tables[0];
- ///
- /// // Get all of the Pictures in this Table.
- /// List<Picture> pictures = t.Pictures;
- ///
- /// // Save this document.
- /// document.Save();
- /// }
- /// ]]>
- /// </code>
- /// </example>
- public List<Picture> Pictures
- {
- get
- {
- var pictures = new List<Picture>();
-
- foreach (Row r in Rows)
- pictures.AddRange(r.Pictures);
-
- return pictures;
- }
- }
-
- /// <summary>
- /// Set the direction of all content in this Table.
- /// </summary>
- /// <param name="direction">(Left to Right) or (Right to Left)</param>
- /// <example>
- /// Set the content direction for all content in a table to RightToLeft.
- /// <code>
- /// // Load a document.
- /// using (DocX document = DocX.Load(@"Test.docx"))
- /// {
- /// // Get the first table in a document.
- /// Table table = document.Tables[0];
- ///
- /// // Set the content direction for all content in this table to RightToLeft.
- /// table.SetDirection(Direction.RightToLeft);
- ///
- /// // Save all changes made to this document.
- /// document.Save();
- /// }
- /// </code>
- /// </example>
- public void SetDirection(Direction direction)
- {
- XElement tblPr = GetOrCreate_tblPr();
- tblPr.Add(new XElement(DocX.w + "bidiVisual"));
-
- foreach (Row r in Rows)
- r.SetDirection(direction);
- }
-
- /// <summary>
- /// Get all of the Hyperlinks in this Table.
- /// </summary>
- /// <example>
- /// Get all of the Hyperlinks in this Table.
- /// <code>
- /// // Create a document.
- /// using (DocX document = DocX.Load(@"Test.docx"))
- /// {
- /// // Get the first Table in this document.
- /// Table t = document.Tables[0];
- ///
- /// // Get a list of all Hyperlinks in this Table.
- /// List<Hyperlink> hyperlinks = t.Hyperlinks;
- ///
- /// // Save this document.
- /// document.Save();
- /// }
- /// </code>
- /// </example>
- public List<Hyperlink> Hyperlinks
- {
- get
- {
- var hyperlinks = new List<Hyperlink>();
-
- foreach (Row r in Rows)
- hyperlinks.AddRange(r.Hyperlinks);
-
- return hyperlinks;
- }
- }
-
- public void SetWidths(float[] widths)
- {
- this.ColumnWidthsValue = widths;
- //set widths for existing rows
- foreach (var r in Rows)
- {
- for (var c = 0; c < widths.Length; c++)
- {
- if (r.Cells.Count > c)
- r.Cells[c].Width = widths[c];
- }
-
- }
- }
-
- /// <summary>
- /// Set Table column width by prescribing percent
- /// </summary>
- /// <param name="widthsPercentage">column width % list</param>
- /// <param name="totalWidth">Total table width. Will be calculated if null sent.</param>
- public void SetWidthsPercentage(float[] widthsPercentage, float? totalWidth)
- {
- if (totalWidth == null) totalWidth = this.Document.PageWidth - this.Document.MarginLeft - this.Document.MarginRight; // calculate total table width
- List<float> widths = new List<float>(widthsPercentage.Length); // empty list, will hold actual width
- widthsPercentage.ToList().ForEach(pWidth => { widths.Add((pWidth * totalWidth.Value / 100) * (96 / 72)); }); // convert percentage to actual width for all values in array
- SetWidths(widths.ToArray()); // set actual column width
- }
-
-
- /// <summary>
- /// If the tblPr element doesent exist it is created, either way it is returned by this function.
- /// </summary>
- /// <returns>The tblPr element for this Table.</returns>
- internal XElement GetOrCreate_tblPr()
- {
- // Get the element.
- XElement tblPr = Xml.Element(XName.Get("tblPr", DocX.w.NamespaceName));
-
- // If it dosen't exist, create it.
- if (tblPr == null)
- {
- Xml.AddFirst(new XElement(XName.Get("tblPr", DocX.w.NamespaceName)));
- tblPr = Xml.Element(XName.Get("tblPr", DocX.w.NamespaceName));
- }
-
- // Return the pPr element for this Paragraph.
- return tblPr;
- }
-
- #pragma warning disable CS1584 // XML comment has syntactically incorrect cref attribute
- /// <summary>
- /// Set the specified cell margin for the table-level.
- /// </summary>
- /// <param name="type">The side of the cell margin.</param>
- /// <param name="margin">The value for the specified cell margin.</param>
- /// <remarks>More information can be found <see cref="http://msdn.microsoft.com/en-us/library/documentformat.openxml.wordprocessing.tablecellmargindefault.aspx">here</see></remarks>
- public void SetTableCellMargin(TableCellMarginType type, double margin)
- #pragma warning restore CS1584 // XML comment has syntactically incorrect cref attribute
- {
- XElement tblPr = GetOrCreate_tblPr();
-
- // find (or create) the element with the cell margins
- XElement tblCellMar = tblPr.Element(XName.Get("tblCellMar", DocX.w.NamespaceName));
- if (tblCellMar == null)
- {
- tblPr.AddFirst(new XElement(XName.Get("tblCellMar", DocX.w.NamespaceName)));
- tblCellMar = tblPr.Element(XName.Get("tblCellMar", DocX.w.NamespaceName));
- }
-
- // find (or create) the element with cell margin for the specified side
- XElement tblMargin = tblCellMar.Element(XName.Get(type.ToString(), DocX.w.NamespaceName));
- if (tblMargin == null)
- {
- tblCellMar.AddFirst(new XElement(XName.Get(type.ToString(), DocX.w.NamespaceName)));
- tblMargin = tblCellMar.Element(XName.Get(type.ToString(), DocX.w.NamespaceName));
- }
-
- tblMargin.RemoveAttributes();
- // set the value for the cell margin
- tblMargin.Add(new XAttribute(XName.Get("w", DocX.w.NamespaceName), margin));
- // set the side of cell margin
- tblMargin.Add(new XAttribute(XName.Get("type", DocX.w.NamespaceName), "dxa"));
- }
-
- /// <summary>
- /// Gets the column width for a given column index.
- /// </summary>
- /// <param name="index"></param>
- public Double GetColumnWidth(Int32 index)
- {
- List<Double> widths = ColumnWidths;
- if (widths == null || index > widths.Count - 1) return Double.NaN;
-
- return widths[index];
- }
-
- /// <summary>
- /// Sets the column width for the given index.
- /// </summary>
- /// <param name="index">Column index</param>
- /// <param name="width">Colum width</param>
- public void SetColumnWidth(Int32 index, Double width)
- {
- List<Double> widths = ColumnWidths;
- if (widths == null || index > widths.Count - 1)
- {
- if (Rows.Count == 0) throw new Exception("There is at least one row required to detect the existing columns.");
- // use width of last row cells
- // may not work for merged cell!
- widths = new List<Double>();
- foreach (Cell c in Rows[Rows.Count - 1].Cells)
- {
- widths.Add(c.Width);
- }
- }
-
- // check if index is matching table columns
- if (index > widths.Count - 1) throw new Exception("The index is greather than the available table columns.");
-
- // get the table grid props
- XElement grid = Xml.Element(XName.Get("tblGrid", DocX.w.NamespaceName));
- // if null; append a new grid below tblPr
- if (grid == null)
- {
- XElement tblPr = GetOrCreate_tblPr();
- tblPr.AddAfterSelf(new XElement(XName.Get("tblGrid", DocX.w.NamespaceName)));
- grid = Xml.Element(XName.Get("tblGrid", DocX.w.NamespaceName));
- }
-
- // remove all existing values
- grid?.RemoveAll();
-
- // append new column widths
- Int32 i = 0;
- foreach (var w in widths)
- {
- double value = w;
- if (i == index) value = width;
- var gridCol = new XElement(XName.Get("gridCol", DocX.w.NamespaceName),
- new XAttribute(XName.Get("w", DocX.w.NamespaceName), value));
- grid?.Add(gridCol);
- i += 1;
- }
-
- // remove cell widths
- foreach (Row r in Rows)
- foreach (Cell c in r.Cells)
- c.Width = -1;
-
- // set fitting to fixed; this will add/set additional table properties
- this.AutoFit = AutoFit.Fixed;
- }
-
-
- /// <summary>
- /// Gets a list of all column widths for this table.
- /// </summary>
- public List<Double> ColumnWidths
- {
- get
- {
- var widths = new List<Double>();
- // get the table grid props
- XElement grid = Xml.Element(XName.Get("tblGrid", DocX.w.NamespaceName));
-
- // get col properties
- var cols = grid?.Elements(XName.Get("gridCol", DocX.w.NamespaceName));
- if (cols == null) return null;
-
- foreach (var col in cols)
- {
- string value = col.GetAttribute(XName.Get("w", DocX.w.NamespaceName));
- widths.Add(Convert.ToDouble(value));
- }
- return widths;
- }
- }
-
-
- /// <summary>
- /// Returns the number of rows in this table.
- /// </summary>
- public Int32 RowCount
- {
- get
- {
- return Xml.Elements(XName.Get("tr", DocX.w.NamespaceName)).Count();
- }
- }
-
- private int _cachedColCount = -1;
- /// <summary>
- /// Returns the number of columns in this table.
- /// </summary>
- public Int32 ColumnCount
- {
- get
- {
- if (RowCount == 0)
- return 0;
- if (_cachedColCount == -1)
- _cachedColCount = Rows.First().ColumnCount;
- return _cachedColCount;
- }
- }
-
- /// <summary>
- /// Returns a list of rows in this table.
- /// </summary>
- public List<Row> Rows
- {
- get
- {
- List<Row> rows =
- (
- from r in Xml.Elements(XName.Get("tr", DocX.w.NamespaceName))
- select new Row(this, Document, r)
- ).ToList();
-
- return rows;
- }
- }
-
- private TableDesign design;
-
-
- internal Table(DocX document, XElement xml)
- : base(document, xml)
- {
- autofit = AutoFit.ColumnWidth;
- this.Xml = xml;
- this.mainPart = document.mainPart;
-
- XElement properties = xml.Element(XName.Get("tblPr", DocX.w.NamespaceName));
-
- XElement style = properties?.Element(XName.Get("tblStyle", DocX.w.NamespaceName));
- if (style != null)
- {
- XAttribute val = style.Attribute(XName.Get("val", DocX.w.NamespaceName));
-
- if (val != null)
- {
- String cleanValue = val.Value.Replace("-", string.Empty);
- if (Enum.IsDefined(typeof(TableDesign), cleanValue))
- {
- design = (TableDesign)Enum.Parse(typeof(TableDesign), cleanValue);
- }
- else
- {
- design = TableDesign.Custom;
- }
- }
- else
- design = TableDesign.None;
- }
-
- else
- design = TableDesign.None;
-
- XElement tableLook = properties?.Element(XName.Get("tblLook", DocX.w.NamespaceName));
- if (tableLook != null)
- {
- TableLook = new TableLook
- {
- FirstRow = tableLook.GetAttribute(XName.Get("firstRow", DocX.w.NamespaceName)) == "1",
- LastRow = tableLook.GetAttribute(XName.Get("lastRow", DocX.w.NamespaceName)) == "1",
- FirstColumn = tableLook.GetAttribute(XName.Get("firstColumn", DocX.w.NamespaceName)) == "1",
- LastColumn = tableLook.GetAttribute(XName.Get("lastColumn", DocX.w.NamespaceName)) == "1",
- NoHorizontalBanding = tableLook.GetAttribute(XName.Get("noHBand", DocX.w.NamespaceName)) == "1",
- NoVerticalBanding = tableLook.GetAttribute(XName.Get("noVBand", DocX.w.NamespaceName)) == "1"
- };
- }
-
- }
- /// <summary>
- /// Extra property for Custom Table Style provided by carpfisher - Thanks
- /// </summary>
- private string _customTableDesignName;
- /// <summary>
- /// Extra property for Custom Table Style provided by carpfisher - Thanks
- /// </summary>
- public string CustomTableDesignName
- {
- set
- {
- _customTableDesignName = value;
- this.Design = TableDesign.Custom;
- }
-
- get
- {
- return _customTableDesignName;
- }
- }
-
- /// <summary>
- /// String containing the Table Caption value (the table's Alternate Text Title)
- /// </summary>
- private string _tableCaption;
- /// <summary>
- /// Gets or Sets the value of the Table Caption (Alternate Text Title) of this table.
- /// </summary>
- public string TableCaption
- {
- set
- {
- XElement tblPr = Xml.Element(XName.Get("tblPr", DocX.w.NamespaceName));
- if (tblPr != null)
- {
- XElement tblCaption =
- tblPr.Descendants(XName.Get("tblCaption", DocX.w.NamespaceName)).FirstOrDefault();
-
- if (tblCaption != null)
- tblCaption.Remove();
-
- tblCaption = new XElement(XName.Get("tblCaption", DocX.w.NamespaceName),
- new XAttribute(XName.Get("val", DocX.w.NamespaceName), value));
- tblPr.Add(tblCaption);
- }
- }
-
- get
- {
- XElement tblPr = Xml.Element(XName.Get("tblPr", DocX.w.NamespaceName));
- XElement caption = tblPr?.Element(XName.Get("tblCaption", DocX.w.NamespaceName));
- if (caption != null)
- {
- _tableCaption = caption.GetAttribute(XName.Get("val", DocX.w.NamespaceName));
- }
- return _tableCaption;
- }
- }
-
- /// <summary>
- /// String containing the Table Description (the table's Alternate Text Description).
- /// </summary>
- private string _tableDescription;
- /// <summary>
- /// Gets or Sets the value of the Table Description (Alternate Text Description) of this table.
- /// </summary>
- public string TableDescription
- {
- set
- {
- XElement tblPr = Xml.Element(XName.Get("tblPr", DocX.w.NamespaceName));
- if (tblPr != null)
- {
- XElement tblDescription =
- tblPr.Descendants(XName.Get("tblDescription", DocX.w.NamespaceName)).FirstOrDefault();
-
- tblDescription?.Remove();
-
- tblDescription = new XElement(XName.Get("tblDescription", DocX.w.NamespaceName),
- new XAttribute(XName.Get("val", DocX.w.NamespaceName), value));
- tblPr.Add(tblDescription);
- }
- }
-
- get
- {
- XElement tblPr = Xml.Element(XName.Get("tblPr", DocX.w.NamespaceName));
- XElement caption = tblPr?.Element(XName.Get("tblDescription", DocX.w.NamespaceName));
- if (caption != null)
- {
- _tableDescription = caption.GetAttribute(XName.Get("val", DocX.w.NamespaceName));
- }
- return _tableDescription;
- }
- }
-
-
- public TableLook TableLook { get; set; }
-
- public Alignment Alignment
- {
- get { return alignment; }
- set
- {
- string alignmentString = string.Empty;
- switch (value)
- {
- case Alignment.left:
- {
- alignmentString = "left";
- break;
- }
-
- case Alignment.both:
- {
- alignmentString = "both";
- break;
- }
-
-
- case Alignment.right:
- {
- alignmentString = "right";
- break;
- }
-
- case Alignment.center:
- {
- alignmentString = "center";
- break;
- }
- }
-
- XElement tblPr = Xml.Descendants(XName.Get("tblPr", DocX.w.NamespaceName)).First();
- XElement jc = tblPr.Descendants(XName.Get("jc", DocX.w.NamespaceName)).FirstOrDefault();
-
- jc?.Remove();
-
- jc = new XElement(XName.Get("jc", DocX.w.NamespaceName), new XAttribute(XName.Get("val", DocX.w.NamespaceName), alignmentString));
- tblPr.Add(jc);
- alignment = value;
- }
- }
-
- /// <summary>
- /// Auto size this table according to some rule.
- /// </summary>
- /// <remarks>Added by Roger Saele, April 2012. Thank you for your contribution Roger.</remarks>
- public AutoFit AutoFit
- {
- get { return autofit; }
-
- set
- {
- string tableAttributeValue = string.Empty;
- string columnAttributeValue = string.Empty;
- switch (value)
- {
- case AutoFit.ColumnWidth:
- {
- tableAttributeValue = "auto";
- columnAttributeValue = "dxa";
-
- // Disable "Automatically resize to fit contents" option
- XElement tblPr = Xml.Element(XName.Get("tblPr", DocX.w.NamespaceName));
- if (tblPr != null)
- {
- XElement layout = tblPr.Element(XName.Get("tblLayout", DocX.w.NamespaceName));
- if (layout == null)
- {
- tblPr.Add(new XElement(XName.Get("tblLayout", DocX.w.NamespaceName)));
- layout = tblPr.Element(XName.Get("tblLayout", DocX.w.NamespaceName));
- }
-
- XAttribute type = layout.Attribute(XName.Get("type", DocX.w.NamespaceName));
- if (type == null)
- {
- layout.Add(new XAttribute(XName.Get("type", DocX.w.NamespaceName), String.Empty));
- type = layout.Attribute(XName.Get("type", DocX.w.NamespaceName));
- }
-
- type.Value = "fixed";
- }
-
- break;
- }
-
- case AutoFit.Contents:
- {
- tableAttributeValue = columnAttributeValue = "auto";
- break;
- }
-
- case AutoFit.Window:
- {
- tableAttributeValue = columnAttributeValue = "pct";
- break;
- }
-
- case AutoFit.Fixed:
- // DL added - 20150816:
- // Set fixed width for the whole table; columns width is definied in the node: tblGrid
- {
- tableAttributeValue = columnAttributeValue = "dxa";
-
- XElement tblPr = Xml.Element(XName.Get("tblPr", DocX.w.NamespaceName));
- XElement tblLayout = tblPr.Element(XName.Get("tblLayout", DocX.w.NamespaceName));
-
- if (tblLayout == null)
- {
- XElement tmp = tblPr.Element(XName.Get("tblInd", DocX.w.NamespaceName)) ??
- tblPr.Element(XName.Get("tblW", DocX.w.NamespaceName));
-
- tmp.AddAfterSelf(new XElement(XName.Get("tblLayout", DocX.w.NamespaceName)));
- tmp = tblPr.Element(XName.Get("tblLayout", DocX.w.NamespaceName));
- tmp.SetAttributeValue(XName.Get("type", DocX.w.NamespaceName), "fixed");
-
- tmp = tblPr.Element(XName.Get("tblW", DocX.w.NamespaceName));
- Double i = 0;
- foreach (Double w in ColumnWidths)
- i += w;
-
- tmp.SetAttributeValue(XName.Get("w", DocX.w.NamespaceName), i.ToString());
-
-
- break;
-
- }
- else
- {
- var qry = from d in Xml.Descendants()
- let type = d.Attribute(XName.Get("type", DocX.w.NamespaceName))
- where (d.Name.LocalName == "tblLayout") && type != null
- select type;
-
- foreach (XAttribute type in qry)
- type.Value = "fixed";
-
-
- XElement tmp = tblPr.Element(XName.Get("tblW", DocX.w.NamespaceName));
- Double i = 0;
- foreach (Double w in ColumnWidths)
- i += w;
-
- tmp.SetAttributeValue(XName.Get("w", DocX.w.NamespaceName), i.ToString());
- break;
- }
-
- }
- }
-
- // Set table attributes
- var query = from d in Xml.Descendants()
- let type = d.Attribute(XName.Get("type", DocX.w.NamespaceName))
- where (d.Name.LocalName == "tblW") && type != null
- select type;
-
- foreach (XAttribute type in query)
- type.Value = tableAttributeValue;
-
- // Set column attributes
- query = from d in Xml.Descendants()
- let type = d.Attribute(XName.Get("type", DocX.w.NamespaceName))
- where (d.Name.LocalName == "tcW") && type != null
- select type;
-
- foreach (XAttribute type in query)
- type.Value = columnAttributeValue;
-
- autofit = value;
- }
- }
- /// <summary>
- /// The design\style to apply to this table.
- ///
- /// Patch1. Patch to code for Custom Table Style support by carpfisher
- /// </summary>
- /// <example>
- /// Example code for custom table style usage
- ///
- /// <code>
- /// Novacode.DocX document = Novacode.DocX.Load(“DOC01.doc”); // load document with custom table style defined
- /// Novacode.Table t = document.AddTable(2, 2); // adds table
- /// t.CustomTableDesignName = “MyStyle01”; // assigns Custom Table Design style to newly created table
- /// </code>
- /// </example>
- ///
- ///
- ///
- public TableDesign Design
- {
- get { return design; }
- set
- {
- XElement tblPr = Xml.Element(XName.Get("tblPr", DocX.w.NamespaceName));
- XElement style = tblPr.Element(XName.Get("tblStyle", DocX.w.NamespaceName));
- if (style == null)
- {
- tblPr.Add(new XElement(XName.Get("tblStyle", DocX.w.NamespaceName)));
- style = tblPr.Element(XName.Get("tblStyle", DocX.w.NamespaceName));
- }
-
- XAttribute val = style.Attribute(XName.Get("val", DocX.w.NamespaceName));
- if (val == null)
- {
- style.Add(new XAttribute(XName.Get("val", DocX.w.NamespaceName), ""));
- val = style.Attribute(XName.Get("val", DocX.w.NamespaceName));
- }
-
- design = value;
-
- if (design == TableDesign.None)
- style.Remove();
-
- if (design == TableDesign.Custom)
- {
- #region Code is commented out
- // The code gives a problem while copiing a table.
- // Look at Test_Clone_Table_Twice method in test.
- //Example:
- //Table tab1 = doc.Tables[ 0 ];
- //Table tab2 = doc.InsertTable( tab1 );
- //Table tab3 = doc.InsertTable( tab2 ); - here we have exception at "var styleElement =" line below in this method
- // The source of the problem is loosing the "<w:tblStyle w:val="a3"/>" by the commented code
-
- //if (string.IsNullOrEmpty(_customTableDesignName))
- //{
- // design = TableDesign.None;
- // if (style != null)
- // style.Remove();
-
- //}
- //else
- //{
- // val.Value = _customTableDesignName;
- //}
- #endregion
- }
- else
- {
- switch (design)
- {
- case TableDesign.TableNormal:
- val.Value = "TableNormal";
- break;
- case TableDesign.TableGrid:
- val.Value = "TableGrid";
- break;
- case TableDesign.LightShading:
- val.Value = "LightShading";
- break;
- case TableDesign.LightShadingAccent1:
- val.Value = "LightShading-Accent1";
- break;
- case TableDesign.LightShadingAccent2:
- val.Value = "LightShading-Accent2";
- break;
- case TableDesign.LightShadingAccent3:
- val.Value = "LightShading-Accent3";
- break;
- case TableDesign.LightShadingAccent4:
- val.Value = "LightShading-Accent4";
- break;
- case TableDesign.LightShadingAccent5:
- val.Value = "LightShading-Accent5";
- break;
- case TableDesign.LightShadingAccent6:
- val.Value = "LightShading-Accent6";
- break;
- case TableDesign.LightList:
- val.Value = "LightList";
- break;
- case TableDesign.LightListAccent1:
- val.Value = "LightList-Accent1";
- break;
- case TableDesign.LightListAccent2:
- val.Value = "LightList-Accent2";
- break;
- case TableDesign.LightListAccent3:
- val.Value = "LightList-Accent3";
- break;
- case TableDesign.LightListAccent4:
- val.Value = "LightList-Accent4";
- break;
- case TableDesign.LightListAccent5:
- val.Value = "LightList-Accent5";
- break;
- case TableDesign.LightListAccent6:
- val.Value = "LightList-Accent6";
- break;
- case TableDesign.LightGrid:
- val.Value = "LightGrid";
- break;
- case TableDesign.LightGridAccent1:
- val.Value = "LightGrid-Accent1";
- break;
- case TableDesign.LightGridAccent2:
- val.Value = "LightGrid-Accent2";
- break;
- case TableDesign.LightGridAccent3:
- val.Value = "LightGrid-Accent3";
- break;
- case TableDesign.LightGridAccent4:
- val.Value = "LightGrid-Accent4";
- break;
- case TableDesign.LightGridAccent5:
- val.Value = "LightGrid-Accent5";
- break;
- case TableDesign.LightGridAccent6:
- val.Value = "LightGrid-Accent6";
- break;
- case TableDesign.MediumShading1:
- val.Value = "MediumShading1";
- break;
- case TableDesign.MediumShading1Accent1:
- val.Value = "MediumShading1-Accent1";
- break;
- case TableDesign.MediumShading1Accent2:
- val.Value = "MediumShading1-Accent2";
- break;
- case TableDesign.MediumShading1Accent3:
- val.Value = "MediumShading1-Accent3";
- break;
- case TableDesign.MediumShading1Accent4:
- val.Value = "MediumShading1-Accent4";
- break;
- case TableDesign.MediumShading1Accent5:
- val.Value = "MediumShading1-Accent5";
- break;
- case TableDesign.MediumShading1Accent6:
- val.Value = "MediumShading1-Accent6";
- break;
- case TableDesign.MediumShading2:
- val.Value = "MediumShading2";
- break;
- case TableDesign.MediumShading2Accent1:
- val.Value = "MediumShading2-Accent1";
- break;
- case TableDesign.MediumShading2Accent2:
- val.Value = "MediumShading2-Accent2";
- break;
- case TableDesign.MediumShading2Accent3:
- val.Value = "MediumShading2-Accent3";
- break;
- case TableDesign.MediumShading2Accent4:
- val.Value = "MediumShading2-Accent4";
- break;
- case TableDesign.MediumShading2Accent5:
- val.Value = "MediumShading2-Accent5";
- break;
- case TableDesign.MediumShading2Accent6:
- val.Value = "MediumShading2-Accent6";
- break;
- case TableDesign.MediumList1:
- val.Value = "MediumList1";
- break;
- case TableDesign.MediumList1Accent1:
- val.Value = "MediumList1-Accent1";
- break;
- case TableDesign.MediumList1Accent2:
- val.Value = "MediumList1-Accent2";
- break;
- case TableDesign.MediumList1Accent3:
- val.Value = "MediumList1-Accent3";
- break;
- case TableDesign.MediumList1Accent4:
- val.Value = "MediumList1-Accent4";
- break;
- case TableDesign.MediumList1Accent5:
- val.Value = "MediumList1-Accent5";
- break;
- case TableDesign.MediumList1Accent6:
- val.Value = "MediumList1-Accent6";
- break;
- case TableDesign.MediumList2:
- val.Value = "MediumList2";
- break;
- case TableDesign.MediumList2Accent1:
- val.Value = "MediumList2-Accent1";
- break;
- case TableDesign.MediumList2Accent2:
- val.Value = "MediumList2-Accent2";
- break;
- case TableDesign.MediumList2Accent3:
- val.Value = "MediumList2-Accent3";
- break;
- case TableDesign.MediumList2Accent4:
- val.Value = "MediumList2-Accent4";
- break;
- case TableDesign.MediumList2Accent5:
- val.Value = "MediumList2-Accent5";
- break;
- case TableDesign.MediumList2Accent6:
- val.Value = "MediumList2-Accent6";
- break;
- case TableDesign.MediumGrid1:
- val.Value = "MediumGrid1";
- break;
- case TableDesign.MediumGrid1Accent1:
- val.Value = "MediumGrid1-Accent1";
- break;
- case TableDesign.MediumGrid1Accent2:
- val.Value = "MediumGrid1-Accent2";
- break;
- case TableDesign.MediumGrid1Accent3:
- val.Value = "MediumGrid1-Accent3";
- break;
- case TableDesign.MediumGrid1Accent4:
- val.Value = "MediumGrid1-Accent4";
- break;
- case TableDesign.MediumGrid1Accent5:
- val.Value = "MediumGrid1-Accent5";
- break;
- case TableDesign.MediumGrid1Accent6:
- val.Value = "MediumGrid1-Accent6";
- break;
- case TableDesign.MediumGrid2:
- val.Value = "MediumGrid2";
- break;
- case TableDesign.MediumGrid2Accent1:
- val.Value = "MediumGrid2-Accent1";
- break;
- case TableDesign.MediumGrid2Accent2:
- val.Value = "MediumGrid2-Accent2";
- break;
- case TableDesign.MediumGrid2Accent3:
- val.Value = "MediumGrid2-Accent3";
- break;
- case TableDesign.MediumGrid2Accent4:
- val.Value = "MediumGrid2-Accent4";
- break;
- case TableDesign.MediumGrid2Accent5:
- val.Value = "MediumGrid2-Accent5";
- break;
- case TableDesign.MediumGrid2Accent6:
- val.Value = "MediumGrid2-Accent6";
- break;
- case TableDesign.MediumGrid3:
- val.Value = "MediumGrid3";
- break;
- case TableDesign.MediumGrid3Accent1:
- val.Value = "MediumGrid3-Accent1";
- break;
- case TableDesign.MediumGrid3Accent2:
- val.Value = "MediumGrid3-Accent2";
- break;
- case TableDesign.MediumGrid3Accent3:
- val.Value = "MediumGrid3-Accent3";
- break;
- case TableDesign.MediumGrid3Accent4:
- val.Value = "MediumGrid3-Accent4";
- break;
- case TableDesign.MediumGrid3Accent5:
- val.Value = "MediumGrid3-Accent5";
- break;
- case TableDesign.MediumGrid3Accent6:
- val.Value = "MediumGrid3-Accent6";
- break;
-
- case TableDesign.DarkList:
- val.Value = "DarkList";
- break;
- case TableDesign.DarkListAccent1:
- val.Value = "DarkList-Accent1";
- break;
- case TableDesign.DarkListAccent2:
- val.Value = "DarkList-Accent2";
- break;
- case TableDesign.DarkListAccent3:
- val.Value = "DarkList-Accent3";
- break;
- case TableDesign.DarkListAccent4:
- val.Value = "DarkList-Accent4";
- break;
- case TableDesign.DarkListAccent5:
- val.Value = "DarkList-Accent5";
- break;
- case TableDesign.DarkListAccent6:
- val.Value = "DarkList-Accent6";
- break;
-
- case TableDesign.ColorfulShading:
- val.Value = "ColorfulShading";
- break;
- case TableDesign.ColorfulShadingAccent1:
- val.Value = "ColorfulShading-Accent1";
- break;
- case TableDesign.ColorfulShadingAccent2:
- val.Value = "ColorfulShading-Accent2";
- break;
- case TableDesign.ColorfulShadingAccent3:
- val.Value = "ColorfulShading-Accent3";
- break;
- case TableDesign.ColorfulShadingAccent4:
- val.Value = "ColorfulShading-Accent4";
- break;
- case TableDesign.ColorfulShadingAccent5:
- val.Value = "ColorfulShading-Accent5";
- break;
- case TableDesign.ColorfulShadingAccent6:
- val.Value = "ColorfulShading-Accent6";
- break;
-
- case TableDesign.ColorfulList:
- val.Value = "ColorfulList";
- break;
- case TableDesign.ColorfulListAccent1:
- val.Value = "ColorfulList-Accent1";
- break;
- case TableDesign.ColorfulListAccent2:
- val.Value = "ColorfulList-Accent2";
- break;
- case TableDesign.ColorfulListAccent3:
- val.Value = "ColorfulList-Accent3";
- break;
- case TableDesign.ColorfulListAccent4:
- val.Value = "ColorfulList-Accent4";
- break;
- case TableDesign.ColorfulListAccent5:
- val.Value = "ColorfulList-Accent5";
- break;
- case TableDesign.ColorfulListAccent6:
- val.Value = "ColorfulList-Accent6";
- break;
-
- case TableDesign.ColorfulGrid:
- val.Value = "ColorfulGrid";
- break;
- case TableDesign.ColorfulGridAccent1:
- val.Value = "ColorfulGrid-Accent1";
- break;
- case TableDesign.ColorfulGridAccent2:
- val.Value = "ColorfulGrid-Accent2";
- break;
- case TableDesign.ColorfulGridAccent3:
- val.Value = "ColorfulGrid-Accent3";
- break;
- case TableDesign.ColorfulGridAccent4:
- val.Value = "ColorfulGrid-Accent4";
- break;
- case TableDesign.ColorfulGridAccent5:
- val.Value = "ColorfulGrid-Accent5";
- break;
- case TableDesign.ColorfulGridAccent6:
- val.Value = "ColorfulGrid-Accent6";
- break;
- }
- }
- if (Document.styles == null)
- {
- PackagePart word_styles = Document.package.GetPart(new Uri("/word/styles.xml", UriKind.Relative));
- using (TextReader tr = new StreamReader(word_styles.GetStream()))
- Document.styles = XDocument.Load(tr);
- }
-
- var tableStyle =
- (
- from e in Document.styles.Descendants()
- let styleId = e.Attribute(XName.Get("styleId", DocX.w.NamespaceName))
- where (styleId != null && styleId.Value == val.Value)
- select e
- ).FirstOrDefault();
-
- if (tableStyle == null)
- {
- XDocument external_style_doc = HelperFunctions.DecompressXMLResource("Novacode.Resources.styles.xml.gz");
-
- var styleElement =
- (
- from e in external_style_doc.Descendants()
- let styleId = e.Attribute(XName.Get("styleId", DocX.w.NamespaceName))
- where (styleId != null && styleId.Value == val.Value)
- select e
- ).FirstOrDefault();
-
- if( styleElement != null )
- Document.styles.Element(XName.Get("styles", DocX.w.NamespaceName)).Add(styleElement);
- }
- }
- }
-
- /// <summary>
- /// Returns the index of this Table.
- /// </summary>
- /// <example>
- /// Replace the first table in this document with a new Table.
- /// <code>
- /// // Load a document into memory.
- /// using (DocX document = DocX.Load(@"Test.docx"))
- /// {
- /// // Get the first Table in this document.
- /// Table t = document.Tables[0];
- ///
- /// // Get the character index of Table t in this document.
- /// int index = t.Index;
- ///
- /// // Remove Table t.
- /// t.Remove();
- ///
- /// // Insert a new Table at the original index of Table t.
- /// Table newTable = document.InsertTable(index, 4, 4);
- ///
- /// // Set the design of this new Table, so that we can see it.
- /// newTable.Design = TableDesign.LightShadingAccent1;
- ///
- /// // Save all changes made to the document.
- /// document.Save();
- /// } // Release this document from memory.
- /// </code>
- /// </example>
- public int Index
- {
- get
- {
- int index = 0;
- IEnumerable<XElement> previous = Xml.ElementsBeforeSelf();
-
- foreach (XElement e in previous)
- index += Paragraph.GetElementTextLength(e);
-
- return index;
- }
- }
-
- /// <summary>
- /// Remove this Table from this document.
- /// </summary>
- /// <example>
- /// Remove the first Table from this document.
- /// <code>
- /// // Load a document into memory.
- /// using (DocX document = DocX.Load(@"Test.docx"))
- /// {
- /// // Get the first Table in this document.
- /// Table t = d.Tables[0];
- ///
- /// // Remove this Table.
- /// t.Remove();
- ///
- /// // Save all changes made to the document.
- /// document.Save();
- /// } // Release this document from memory.
- /// </code>
- /// </example>
- public void Remove()
- {
- Xml.Remove();
- }
-
- /// <summary>
- /// Insert a row at the end of this table.
- /// </summary>
- /// <example>
- /// <code>
- /// // Load a document.
- /// using (DocX document = DocX.Load(@"C:\Example\Test.docx"))
- /// {
- /// // Get the first table in this document.
- /// Table table = document.Tables[0];
- ///
- /// // Insert a new row at the end of this table.
- /// Row row = table.InsertRow();
- ///
- /// // Loop through each cell in this new row.
- /// foreach (Cell c in row.Cells)
- /// {
- /// // Set the text of each new cell to "Hello".
- /// c.Paragraphs[0].InsertText("Hello", false);
- /// }
- ///
- /// // Save the document to a new file.
- /// document.SaveAs(@"C:\Example\Test2.docx");
- /// }// Release this document from memory.
- /// </code>
- /// </example>
- /// <returns>A new row.</returns>
- public Row InsertRow()
- {
- return InsertRow(RowCount);
- }
-
- /// <summary>
- /// Insert a copy of a row at the end of this table.
- /// </summary>
- /// <returns>A new row.</returns>
- /// <param name="row">The row to insert</param>
- /// <param name="keepFormatting">True to clone everithing, False to clone cell structure only.</param>
- /// <returns></returns>
- public Row InsertRow(Row row, bool keepFormatting = false)
- {
- return InsertRow(row, RowCount, keepFormatting);
- }
-
- /// <summary>
- /// Insert a column to the right of a Table.
- /// </summary>
- /// <example>
- /// <code>
- /// // Load a document.
- /// using (DocX document = DocX.Load(@"C:\Example\Test.docx"))
- /// {
- /// // Get the first Table in this document.
- /// Table table = document.Tables[0];
- ///
- /// // Insert a new column to this right of this table.
- /// table.InsertColumn();
- ///
- /// // Set the new columns text to "Row no."
- /// table.Rows[0].Cells[table.ColumnCount - 1].Paragraph.InsertText("Row no.", false);
- ///
- /// // Loop through each row in the table.
- /// for (int i = 1; i < table.Rows.Count; i++)
- /// {
- /// // The current row.
- /// Row row = table.Rows[i];
- ///
- /// // The cell in this row that belongs to the new column.
- /// Cell cell = row.Cells[table.ColumnCount - 1];
- ///
- /// // The first Paragraph that this cell houses.
- /// Paragraph p = cell.Paragraphs[0];
- ///
- /// // Insert this rows index.
- /// p.InsertText(i.ToString(), false);
- /// }
- ///
- /// document.Save();
- /// }// Release this document from memory.
- /// </code>
- /// </example>
- public void InsertColumn()
- {
- InsertColumn(ColumnCount, true);
- }
-
- /// <summary>
- /// Remove the last row from this Table.
- /// </summary>
- /// <example>
- /// Remove the last row from a Table.
- /// <code>
- /// // Load a document.
- /// using (DocX document = DocX.Load(@"C:\Example\Test.docx"))
- /// {
- /// // Get the first table in this document.
- /// Table table = document.Tables[0];
- ///
- /// // Remove the last row from this table.
- /// table.RemoveRow();
- ///
- /// // Save the document.
- /// document.Save();
- /// }// Release this document from memory.
- /// </code>
- /// </example>
- public void RemoveRow()
- {
- RemoveRow(RowCount - 1);
- }
-
- /// <summary>
- /// Remove a row from this Table.
- /// </summary>
- /// <param name="index">The row to remove.</param>
- /// <example>
- /// Remove the first row from a Table.
- /// <code>
- /// // Load a document.
- /// using (DocX document = DocX.Load(@"C:\Example\Test.docx"))
- /// {
- /// // Get the first table in this document.
- /// Table table = document.Tables[0];
- ///
- /// // Remove the first row from this table.
- /// table.RemoveRow(0);
- ///
- /// // Save the document.
- /// document.Save();
- /// }// Release this document from memory.
- /// </code>
- /// </example>
- public void RemoveRow(int index)
- {
- if (index < 0 || index > RowCount - 1)
- throw new IndexOutOfRangeException();
-
- Rows[index].Xml.Remove();
- if (Rows.Count == 0)
- Remove();
- }
-
- /// <summary>
- /// Remove the last column for this Table.
- /// </summary>
- /// <example>
- /// Remove the last column from a Table.
- /// <code>
- /// // Load a document.
- /// using (DocX document = DocX.Load(@"C:\Example\Test.docx"))
- /// {
- /// // Get the first table in this document.
- /// Table table = document.Tables[0];
- ///
- /// // Remove the last column from this table.
- /// table.RemoveColumn();
- ///
- /// // Save the document.
- /// document.Save();
- /// }// Release this document from memory.
- /// </code>
- /// </example>
- public void RemoveColumn()
- {
- RemoveColumn(ColumnCount - 1);
- }
-
- /// <summary>
- /// Remove a column from this Table.
- /// </summary>
- /// <param name="index">The column to remove.</param>
- /// <example>
- /// Remove the first column from a Table.
- /// <code>
- /// // Load a document.
- /// using (DocX document = DocX.Load(@"C:\Example\Test.docx"))
- /// {
- /// // Get the first table in this document.
- /// Table table = document.Tables[0];
- ///
- /// // Remove the first column from this table.
- /// table.RemoveColumn(0);
- ///
- /// // Save the document.
- /// document.Save();
- /// }// Release this document from memory.
- /// </code>
- /// </example>
- public void RemoveColumn(int index)
- {
- if (index < 0 || index > ColumnCount - 1)
- throw new IndexOutOfRangeException();
-
- foreach (Row r in Rows)
- if (r.Cells.Count < ColumnCount)
- {
- var positionIndex = 0;
- var actualPosition = 0;
- var gridAfterVal = 0;
- // checks to see if there is a deleted cell
- gridAfterVal = r.gridAfter;
-
- // goes through iteration of cells to find the one the that contains the index number
- foreach (Cell rowCell in r.Cells)
- {
- // checks if the cell has a gridspan
- var gridSpanVal = 0;
-
- if (rowCell.GridSpan != 0)
- {
- gridSpanVal = rowCell.GridSpan - 1;
- }
-
- // checks to see if the index is within its lowest and highest cell value
- if ((index - gridAfterVal) >= actualPosition
- && (index - gridAfterVal) <= (actualPosition + gridSpanVal))
- {
- r.Cells[positionIndex].Xml.Remove();
- break;
- }
- positionIndex += 1;
- actualPosition += gridSpanVal + 1;
- }
- }
- else
- {
- r.Cells[index].Xml.Remove();
- }
-
- _cachedColCount = -1;
- }
-
- /// <summary>
- /// Insert a row into this table.
- /// </summary>
- /// <example>
- /// <code>
- /// // Load a document.
- /// using (DocX document = DocX.Load(@"C:\Example\Test.docx"))
- /// {
- /// // Get the first table in this document.
- /// Table table = document.Tables[0];
- ///
- /// // Insert a new row at index 1 in this table.
- /// Row row = table.InsertRow(1);
- ///
- /// // Loop through each cell in this new row.
- /// foreach (Cell c in row.Cells)
- /// {
- /// // Set the text of each new cell to "Hello".
- /// c.Paragraphs[0].InsertText("Hello", false);
- /// }
- ///
- /// // Save the document to a new file.
- /// document.SaveAs(@"C:\Example\Test2.docx");
- /// }// Release this document from memory.
- /// </code>
- /// </example>
- /// <param name="index">Index to insert row at.</param>
- /// <returns>A new Row</returns>
- public Row InsertRow(int index)
- {
- if (index < 0 || index > RowCount)
- throw new IndexOutOfRangeException();
-
- List<XElement> content = new List<XElement>();
- for (int i = 0; i < ColumnCount; i++)
- {
- var w = 2310d;
- if (ColumnWidthsValue != null && ColumnWidthsValue.Length > i)
- w = ColumnWidthsValue[i] * 15;
- XElement cell = HelperFunctions.CreateTableCell(w);
- content.Add(cell);
- }
-
- return InsertRow(content, index);
- }
-
- /// <summary>
- /// Insert a copy of a row into this table.
- /// </summary>
- /// <param name="row">Row to copy and insert.</param>
- /// <param name="index">Index to insert row at.</param>
- /// <param name="keepFormatting">True to clone everithing, False to clone cell structure only.</param>
- /// <returns>A new Row</returns>
- public Row InsertRow(Row row, int index, bool keepFormatting = false)
- {
- if (row == null)
- throw new ArgumentNullException(nameof(row));
-
- if (index < 0 || index > RowCount)
- throw new IndexOutOfRangeException();
-
- List<XElement> content;
- if( keepFormatting )
- content = row.Xml.Elements().Select(element => HelperFunctions.CloneElement(element)).ToList();
- else
- content = row.Xml.Elements(XName.Get("tc", DocX.w.NamespaceName)).Select(element => HelperFunctions.CloneElement(element)).ToList();
-
- return InsertRow(content, index);
- }
-
- private Row InsertRow(List<XElement> content, Int32 index)
- {
- Row newRow = new Row(this, Document, new XElement(XName.Get("tr", DocX.w.NamespaceName), content));
-
- XElement rowXml;
- if (index == Rows.Count)
- {
- rowXml = Rows.Last().Xml;
- rowXml.AddAfterSelf(newRow.Xml);
- }
-
- else
- {
- rowXml = Rows[index].Xml;
- rowXml.AddBeforeSelf(newRow.Xml);
- }
-
- return newRow;
- }
-
- /// <summary>
- /// Insert a column into a table.
- /// </summary>
- /// <param name="index">The index to insert the column at.</param>
- /// <param name="direction">The side in which you wish to place the colum(True right, false left)</param>
- /// <example>
- /// Insert a column to the left of a table.
- /// <code>
- /// // Load a document.
- /// using (DocX document = DocX.Load(@"C:\Example\Test.docx"))
- /// {
- /// // Get the first Table in this document.
- /// Table table = document.Tables[0];
- ///
- /// // Insert a new column to this left of this table.
- /// table.InsertColumn(0, false);
- ///
- /// // Set the new columns text to "Row no."
- /// table.Rows[0].Cells[table.ColumnCount - 1].Paragraph.InsertText("Row no.", false);
- ///
- /// // Loop through each row in the table.
- /// for (int i = 1; i < table.Rows.Count; i++)
- /// {
- /// // The current row.
- /// Row row = table.Rows[i];
- ///
- /// // The cell in this row that belongs to the new column.
- /// Cell cell = row.Cells[table.ColumnCount - 1];
- ///
- /// // The first Paragraph that this cell houses.
- /// Paragraph p = cell.Paragraphs[0];
- ///
- /// // Insert this rows index.
- /// p.InsertText(i.ToString(), false);
- /// }
- ///
- /// document.Save();
- /// }// Release this document from memory.
- /// </code>
- /// </example>
- public void InsertColumn(int index, bool direction)
- {
- var columnCount = ColumnCount;
- if (RowCount > 0)
- {
- if (index > 0 && index <= columnCount)
- {
- _cachedColCount = -1;
- foreach (Row r in Rows)
- {
- // create cell
- XElement cell = HelperFunctions.CreateTableCell();
-
- // insert cell
- // checks if it is in bounds of index
- if (r.Cells.Count < columnCount)
- {
- if (index >= columnCount)
- {
- AddCellToRow(r, cell, r.Cells.Count, direction);
- }
- else
- {
- var positionIndex = 1;
- var actualPosition = 1;
- var gridAfterVal = 0;
- // checks to see if there is a deleted cell
-
- gridAfterVal = r.gridAfter;
-
- // goes through iteration of cells to find the one the that contains the index number
- foreach (Cell rowCell in r.Cells)
- {
- // checks if the cell has a gridspan
- var gridSpanVal = 0;
-
- if (rowCell.GridSpan != 0)
- {
- gridSpanVal = rowCell.GridSpan - 1;
- }
-
- // checks to see if the index is within its lowest and highest cell value
- if ((index - gridAfterVal) >= actualPosition
- && (index - gridAfterVal) <= (actualPosition + gridSpanVal))
- {
- bool directionTest;
- if (index == (actualPosition + gridSpanVal) && direction)
- {
- directionTest = true;
- }
- else
- {
- directionTest = false;
- }
- AddCellToRow(r, cell, positionIndex, directionTest);
- break;
- }
- positionIndex += 1;
- actualPosition += gridSpanVal + 1;
- }
- }
- }
- else if (r.Cells.Count == index)
- {
- AddCellToRow(r, cell, index, direction);
- }
- else
- AddCellToRow(r, cell, index, direction);
- }
- }
- else
- {
- throw new IndexOutOfRangeException("Out of index bounds, column count is " + columnCount + " you input " + index);
- }
- }
- }
-
- /// <summary>
- /// Adds a cell to the right or left of a cell
- /// </summary>
- /// <param name="row">is the row you are adding</param>
- /// <param name="cell">is the cell you are adding</param>
- /// <param name="index">the cell index position you are refferencing from</param>
- /// <param name="direction">which side of the cell you wish to add cell</param>
-
- private void AddCellToRow(Row row, XElement cell, int index, bool direction)
- {
- index -= 1;
- if (direction)
- {
- row.Cells[index].Xml.AddAfterSelf(cell);
- }
- else
- {
- row.Cells[index].Xml.AddBeforeSelf(cell);
- }
- }
- /// <summary>
- /// Deletes a cell in a row
- /// </summary>
- /// <param name="rowIndex">index of the row you want to remove the cell</param>
- /// <param name="celIndex">index of the cell you want to remove</param>
- public void DeleteAndShiftCellsLeft(int rowIndex, int celIndex)
- {
-
- var trPr = Rows[rowIndex].Xml.Element(XName.Get("trPr", DocX.w.NamespaceName));
- if (trPr != null)
- {
- var gridAfter = trPr.Element(XName.Get("gridAfter", DocX.w.NamespaceName));
- if (gridAfter != null)
- {
- var val = gridAfter.Attribute(XName.Get("val", DocX.w.NamespaceName));
- val.Value = (int.Parse(val.Value) + 1).ToString();
- }
- else
- {
- gridAfter.SetAttributeValue("val", 1);
- }
- }
- else
- {
- XElement trPrXElement = new XElement(XName.Get("trPr", DocX.w.NamespaceName));
- XElement gridAfterElement = new XElement(XName.Get("gridAfter", DocX.w.NamespaceName));
- XAttribute gridAfterValAttribute = new XAttribute(XName.Get("val", DocX.w.NamespaceName), 1);
- gridAfterElement.Add(gridAfterValAttribute);
- trPrXElement.Add(gridAfterElement);
- Rows[rowIndex].Xml.AddFirst(trPrXElement);
- }
- var columnCount = this.ColumnCount;
- if (celIndex <= this.ColumnCount && this.Rows[rowIndex].ColumnCount <= this.ColumnCount)
- {
- Rows[rowIndex].Cells[celIndex].Xml.Remove();
- }
- }
-
- /// <summary>
- /// Insert a page break before a Table.
- /// </summary>
- /// <example>
- /// Insert a Table and a Paragraph into a document with a page break between them.
- /// <code>
- /// // Create a new document.
- /// using (DocX document = DocX.Create(@"Test.docx"))
- /// {
- /// // Insert a new Paragraph.
- /// Paragraph p1 = document.InsertParagraph("Paragraph", false);
- ///
- /// // Insert a new Table.
- /// Table t1 = document.InsertTable(2, 2);
- /// t1.Design = TableDesign.LightShadingAccent1;
- ///
- /// // Insert a page break before this Table.
- /// t1.InsertPageBreakBeforeSelf();
- ///
- /// // Save this document.
- /// document.Save();
- /// }// Release this document from memory.
- /// </code>
- /// </example>
- public override void InsertPageBreakBeforeSelf()
- {
- base.InsertPageBreakBeforeSelf();
- }
-
-
- /// <summary>
- /// Insert a page break after a Table.
- /// </summary>
- /// <example>
- /// Insert a Table and a Paragraph into a document with a page break between them.
- /// <code>
- /// // Create a new document.
- /// using (DocX document = DocX.Create(@"Test.docx"))
- /// {
- /// // Insert a new Table.
- /// Table t1 = document.InsertTable(2, 2);
- /// t1.Design = TableDesign.LightShadingAccent1;
- ///
- /// // Insert a page break after this Table.
- /// t1.InsertPageBreakAfterSelf();
- ///
- /// // Insert a new Paragraph.
- /// Paragraph p1 = document.InsertParagraph("Paragraph", false);
- ///
- /// // Save this document.
- /// document.Save();
- /// }// Release this document from memory.
- /// </code>
- /// </example>
- public override void InsertPageBreakAfterSelf()
- {
- base.InsertPageBreakAfterSelf();
- }
-
- /// <summary>
- /// Insert a new Table before this Table, this Table can be from this document or another document.
- /// </summary>
- /// <param name="t">The Table t to be inserted</param>
- /// <returns>A new Table inserted before this Table.</returns>
- /// <example>
- /// Insert a new Table before this Table.
- /// <code>
- /// // Place holder for a Table.
- /// Table t;
- ///
- /// // Load document a.
- /// using (DocX documentA = DocX.Load(@"a.docx"))
- /// {
- /// // Get the first Table from this document.
- /// t = documentA.Tables[0];
- /// }
- ///
- /// // Load document b.
- /// using (DocX documentB = DocX.Load(@"b.docx"))
- /// {
- /// // Get the first Table in document b.
- /// Table t2 = documentB.Tables[0];
- ///
- /// // Insert the Table from document a before this Table.
- /// Table newTable = t2.InsertTableBeforeSelf(t);
- ///
- /// // Save all changes made to document b.
- /// documentB.Save();
- /// }// Release this document from memory.
- /// </code>
- /// </example>
- public override Table InsertTableBeforeSelf(Table t)
- {
- return base.InsertTableBeforeSelf(t);
- }
-
- /// <summary>
- /// Insert a new Table into this document before this Table.
- /// </summary>
- /// <param name="rowCount">The number of rows this Table should have.</param>
- /// <param name="columnCount">The number of columns this Table should have.</param>
- /// <returns>A new Table inserted before this Table.</returns>
- /// <example>
- /// <code>
- /// // Create a new document.
- /// using (DocX document = DocX.Create(@"Test.docx"))
- /// {
- /// //Insert a Table into this document.
- /// Table t = document.InsertTable(2, 2);
- /// t.Design = TableDesign.LightShadingAccent1;
- /// t.Alignment = Alignment.center;
- ///
- /// // Insert a new Table before this Table.
- /// Table newTable = t.InsertTableBeforeSelf(2, 2);
- /// newTable.Design = TableDesign.LightShadingAccent2;
- /// newTable.Alignment = Alignment.center;
- ///
- /// // Save all changes made to this document.
- /// document.Save();
- /// }// Release this document from memory.
- /// </code>
- /// </example>
- public override Table InsertTableBeforeSelf(int rowCount, int columnCount)
- {
- return base.InsertTableBeforeSelf(rowCount, columnCount);
- }
-
- /// <summary>
- /// Insert a new Table after this Table, this Table can be from this document or another document.
- /// </summary>
- /// <param name="t">The Table t to be inserted</param>
- /// <returns>A new Table inserted after this Table.</returns>
- /// <example>
- /// Insert a new Table after this Table.
- /// <code>
- /// // Place holder for a Table.
- /// Table t;
- ///
- /// // Load document a.
- /// using (DocX documentA = DocX.Load(@"a.docx"))
- /// {
- /// // Get the first Table from this document.
- /// t = documentA.Tables[0];
- /// }
- ///
- /// // Load document b.
- /// using (DocX documentB = DocX.Load(@"b.docx"))
- /// {
- /// // Get the first Table in document b.
- /// Table t2 = documentB.Tables[0];
- ///
- /// // Insert the Table from document a after this Table.
- /// Table newTable = t2.InsertTableAfterSelf(t);
- ///
- /// // Save all changes made to document b.
- /// documentB.Save();
- /// }// Release this document from memory.
- /// </code>
- /// </example>
- public override Table InsertTableAfterSelf(Table t)
- {
- return base.InsertTableAfterSelf(t);
- }
-
- /// <summary>
- /// Insert a new Table into this document after this Table.
- /// </summary>
- /// <param name="rowCount">The number of rows this Table should have.</param>
- /// <param name="columnCount">The number of columns this Table should have.</param>
- /// <returns>A new Table inserted before this Table.</returns>
- /// <example>
- /// <code>
- /// // Create a new document.
- /// using (DocX document = DocX.Create(@"Test.docx"))
- /// {
- /// //Insert a Table into this document.
- /// Table t = document.InsertTable(2, 2);
- /// t.Design = TableDesign.LightShadingAccent1;
- /// t.Alignment = Alignment.center;
- ///
- /// // Insert a new Table after this Table.
- /// Table newTable = t.InsertTableAfterSelf(2, 2);
- /// newTable.Design = TableDesign.LightShadingAccent2;
- /// newTable.Alignment = Alignment.center;
- ///
- /// // Save all changes made to this document.
- /// document.Save();
- /// }// Release this document from memory.
- /// </code>
- /// </example>
- public override Table InsertTableAfterSelf(int rowCount, int columnCount)
- {
- return base.InsertTableAfterSelf(rowCount, columnCount);
- }
-
- /// <summary>
- /// Insert a Paragraph before this Table, this Paragraph may have come from the same or another document.
- /// </summary>
- /// <param name="p">The Paragraph to insert.</param>
- /// <returns>The Paragraph now associated with this document.</returns>
- /// <example>
- /// Take a Paragraph from document a, and insert it into document b before this Table.
- /// <code>
- /// // Place holder for a Paragraph.
- /// Paragraph p;
- ///
- /// // Load document a.
- /// using (DocX documentA = DocX.Load(@"a.docx"))
- /// {
- /// // Get the first paragraph from this document.
- /// p = documentA.Paragraphs[0];
- /// }
- ///
- /// // Load document b.
- /// using (DocX documentB = DocX.Load(@"b.docx"))
- /// {
- /// // Get the first Table in document b.
- /// Table t = documentB.Tables[0];
- ///
- /// // Insert the Paragraph from document a before this Table.
- /// Paragraph newParagraph = t.InsertParagraphBeforeSelf(p);
- ///
- /// // Save all changes made to document b.
- /// documentB.Save();
- /// }// Release this document from memory.
- /// </code>
- /// </example>
- public override Paragraph InsertParagraphBeforeSelf(Paragraph p)
- {
- return base.InsertParagraphBeforeSelf(p);
- }
-
- /// <summary>
- /// Insert a new Paragraph before this Table.
- /// </summary>
- /// <param name="text">The initial text for this new Paragraph.</param>
- /// <returns>A new Paragraph inserted before this Table.</returns>
- /// <example>
- /// Insert a new Paragraph before the first Table in this document.
- /// <code>
- /// // Create a new document.
- /// using (DocX document = DocX.Create(@"Test.docx"))
- /// {
- /// // Insert a Table into this document.
- /// Table t = document.InsertTable(2, 2);
- ///
- /// t.InsertParagraphBeforeSelf("I was inserted before the next Table.");
- ///
- /// // Save all changes made to this new document.
- /// document.Save();
- /// }// Release this new document form memory.
- /// </code>
- /// </example>
- public override Paragraph InsertParagraphBeforeSelf(string text)
- {
- return base.InsertParagraphBeforeSelf(text);
- }
-
- /// <summary>
- /// Insert a new Paragraph before this Table.
- /// </summary>
- /// <param name="text">The initial text for this new Paragraph.</param>
- /// <param name="trackChanges">Should this insertion be tracked as a change?</param>
- /// <returns>A new Paragraph inserted before this Table.</returns>
- /// <example>
- /// Insert a new paragraph before the first Table in this document.
- /// <code>
- /// // Create a new document.
- /// using (DocX document = DocX.Create(@"Test.docx"))
- /// {
- /// // Insert a Table into this document.
- /// Table t = document.InsertTable(2, 2);
- ///
- /// t.InsertParagraphBeforeSelf("I was inserted before the next Table.", false);
- ///
- /// // Save all changes made to this new document.
- /// document.Save();
- /// }// Release this new document form memory.
- /// </code>
- /// </example>
- public override Paragraph InsertParagraphBeforeSelf(string text, bool trackChanges)
- {
- return base.InsertParagraphBeforeSelf(text, trackChanges);
- }
-
- /// <summary>
- /// Insert a new Paragraph before this Table.
- /// </summary>
- /// <param name="text">The initial text for this new Paragraph.</param>
- /// <param name="trackChanges">Should this insertion be tracked as a change?</param>
- /// <param name="formatting">The formatting to apply to this insertion.</param>
- /// <returns>A new Paragraph inserted before this Table.</returns>
- /// <example>
- /// Insert a new paragraph before the first Table in this document.
- /// <code>
- /// // Create a new document.
- /// using (DocX document = DocX.Create(@"Test.docx"))
- /// {
- /// // Insert a Table into this document.
- /// Table t = document.InsertTable(2, 2);
- ///
- /// Formatting boldFormatting = new Formatting();
- /// boldFormatting.Bold = true;
- ///
- /// t.InsertParagraphBeforeSelf("I was inserted before the next Table.", false, boldFormatting);
- ///
- /// // Save all changes made to this new document.
- /// document.Save();
- /// }// Release this new document form memory.
- /// </code>
- /// </example>
- public override Paragraph InsertParagraphBeforeSelf(string text, bool trackChanges, Formatting formatting)
- {
- return base.InsertParagraphBeforeSelf(text, trackChanges, formatting);
- }
-
- /// <summary>
- /// Insert a Paragraph after this Table, this Paragraph may have come from the same or another document.
- /// </summary>
- /// <param name="p">The Paragraph to insert.</param>
- /// <returns>The Paragraph now associated with this document.</returns>
- /// <example>
- /// Take a Paragraph from document a, and insert it into document b after this Table.
- /// <code>
- /// // Place holder for a Paragraph.
- /// Paragraph p;
- ///
- /// // Load document a.
- /// using (DocX documentA = DocX.Load(@"a.docx"))
- /// {
- /// // Get the first paragraph from this document.
- /// p = documentA.Paragraphs[0];
- /// }
- ///
- /// // Load document b.
- /// using (DocX documentB = DocX.Load(@"b.docx"))
- /// {
- /// // Get the first Table in document b.
- /// Table t = documentB.Tables[0];
- ///
- /// // Insert the Paragraph from document a after this Table.
- /// Paragraph newParagraph = t.InsertParagraphAfterSelf(p);
- ///
- /// // Save all changes made to document b.
- /// documentB.Save();
- /// }// Release this document from memory.
- /// </code>
- /// </example>
- public override Paragraph InsertParagraphAfterSelf(Paragraph p)
- {
- return base.InsertParagraphAfterSelf(p);
- }
-
- /// <summary>
- /// Insert a new Paragraph after this Table.
- /// </summary>
- /// <param name="text">The initial text for this new Paragraph.</param>
- /// <param name="trackChanges">Should this insertion be tracked as a change?</param>
- /// <param name="formatting">The formatting to apply to this insertion.</param>
- /// <returns>A new Paragraph inserted after this Table.</returns>
- /// <example>
- /// Insert a new paragraph after the first Table in this document.
- /// <code>
- /// // Create a new document.
- /// using (DocX document = DocX.Create(@"Test.docx"))
- /// {
- /// // Insert a Table into this document.
- /// Table t = document.InsertTable(2, 2);
- ///
- /// Formatting boldFormatting = new Formatting();
- /// boldFormatting.Bold = true;
- ///
- /// t.InsertParagraphAfterSelf("I was inserted after the previous Table.", false, boldFormatting);
- ///
- /// // Save all changes made to this new document.
- /// document.Save();
- /// }// Release this new document form memory.
- /// </code>
- /// </example>
- public override Paragraph InsertParagraphAfterSelf(string text, bool trackChanges, Formatting formatting)
- {
- return base.InsertParagraphAfterSelf(text, trackChanges, formatting);
- }
-
- /// <summary>
- /// Insert a new Paragraph after this Table.
- /// </summary>
- /// <param name="text">The initial text for this new Paragraph.</param>
- /// <param name="trackChanges">Should this insertion be tracked as a change?</param>
- /// <returns>A new Paragraph inserted after this Table.</returns>
- /// <example>
- /// Insert a new paragraph after the first Table in this document.
- /// <code>
- /// // Create a new document.
- /// using (DocX document = DocX.Create(@"Test.docx"))
- /// {
- /// // Insert a Table into this document.
- /// Table t = document.InsertTable(2, 2);
- ///
- /// t.InsertParagraphAfterSelf("I was inserted after the previous Table.", false);
- ///
- /// // Save all changes made to this new document.
- /// document.Save();
- /// }// Release this new document form memory.
- /// </code>
- /// </example>
- public override Paragraph InsertParagraphAfterSelf(string text, bool trackChanges)
- {
- return base.InsertParagraphAfterSelf(text, trackChanges);
- }
-
- /// <summary>
- /// Insert a new Paragraph after this Table.
- /// </summary>
- /// <param name="text">The initial text for this new Paragraph.</param>
- /// <returns>A new Paragraph inserted after this Table.</returns>
- /// <example>
- /// Insert a new Paragraph after the first Table in this document.
- /// <code>
- /// // Create a new document.
- /// using (DocX document = DocX.Create(@"Test.docx"))
- /// {
- /// // Insert a Table into this document.
- /// Table t = document.InsertTable(2, 2);
- ///
- /// t.InsertParagraphAfterSelf("I was inserted after the previous Table.");
- ///
- /// // Save all changes made to this new document.
- /// document.Save();
- /// }// Release this new document form memory.
- /// </code>
- /// </example>
- public override Paragraph InsertParagraphAfterSelf(string text)
- {
- return base.InsertParagraphAfterSelf(text);
- }
-
- /// <summary>
- /// Set a table border
- /// Added by lckuiper @ 20101117
- /// </summary>
- /// <example>
- /// <code>
- /// // Create a new document.
- ///using (DocX document = DocX.Create("Test.docx"))
- ///{
- /// // Insert a table into this document.
- /// Table t = document.InsertTable(3, 3);
- ///
- /// // Create a large blue border.
- /// Border b = new Border(BorderStyle.Tcbs_single, BorderSize.seven, 0, Color.Blue);
- ///
- /// // Set the tables Top, Bottom, Left and Right Borders to b.
- /// t.SetBorder(TableBorderType.Top, b);
- /// t.SetBorder(TableBorderType.Bottom, b);
- /// t.SetBorder(TableBorderType.Left, b);
- /// t.SetBorder(TableBorderType.Right, b);
- ///
- /// // Save the document.
- /// document.Save();
- ///}
- /// </code>
- /// </example>
- /// <param name="borderType">The table border to set</param>
- /// <param name="border">Border object to set the table border</param>
- public void SetBorder(TableBorderType borderType, Border border)
- {
- /*
- * Get the tblPr (table properties) element for this Table,
- * null will be return if no such element exists.
- */
- XElement tblPr = Xml.Element(XName.Get("tblPr", DocX.w.NamespaceName));
- if (tblPr == null)
- {
- Xml.SetElementValue(XName.Get("tblPr", DocX.w.NamespaceName), string.Empty);
- tblPr = Xml.Element(XName.Get("tblPr", DocX.w.NamespaceName));
- }
-
- /*
- * Get the tblBorders (table borders) element for this Table,
- * null will be return if no such element exists.
- */
- XElement tblBorders = tblPr.Element(XName.Get("tblBorders", DocX.w.NamespaceName));
- if (tblBorders == null)
- {
- tblPr.SetElementValue(XName.Get("tblBorders", DocX.w.NamespaceName), string.Empty);
- tblBorders = tblPr.Element(XName.Get("tblBorders", DocX.w.NamespaceName));
- }
-
- /*
- * Get the 'borderType' (table border) element for this Table,
- * null will be return if no such element exists.
- */
- var tbordertype = borderType.ToString();
- // only lower the first char of string (because of insideH and insideV)
- tbordertype = tbordertype.Substring(0, 1).ToLower() + tbordertype.Substring(1);
-
- XElement tblBorderType = tblBorders.Element(XName.Get(borderType.ToString(), DocX.w.NamespaceName));
- if (tblBorderType == null)
- {
- tblBorders.SetElementValue(XName.Get(tbordertype, DocX.w.NamespaceName), string.Empty);
- tblBorderType = tblBorders.Element(XName.Get(tbordertype, DocX.w.NamespaceName));
- }
-
- // get string value of border style
- string borderstyle = border.Tcbs.ToString().Substring(5);
- borderstyle = borderstyle.Substring(0, 1).ToLower() + borderstyle.Substring(1);
-
- // The val attribute is used for the border style
- tblBorderType.SetAttributeValue(XName.Get("val", DocX.w.NamespaceName), borderstyle);
-
- if (border.Tcbs != BorderStyle.Tcbs_nil)
- {
- int size;
- switch (border.Size)
- {
- case BorderSize.one: size = 2; break;
- case BorderSize.two: size = 4; break;
- case BorderSize.three: size = 6; break;
- case BorderSize.four: size = 8; break;
- case BorderSize.five: size = 12; break;
- case BorderSize.six: size = 18; break;
- case BorderSize.seven: size = 24; break;
- case BorderSize.eight: size = 36; break;
- case BorderSize.nine: size = 48; break;
- default: size = 2; break;
- }
-
- // The sz attribute is used for the border size
- tblBorderType.SetAttributeValue(XName.Get("sz", DocX.w.NamespaceName), (size).ToString());
-
- // The space attribute is used for the cell spacing (probably '0')
- tblBorderType.SetAttributeValue(XName.Get("space", DocX.w.NamespaceName), (border.Space).ToString());
-
- // The color attribute is used for the border color
- tblBorderType.SetAttributeValue(XName.Get("color", DocX.w.NamespaceName), border.Color.ToHex());
- }
- }
-
- /// <summary>
- /// Get a table border
- /// Added by lckuiper @ 20101117
- /// </summary>
- /// <param name="borderType">The table border to get</param>
- public Border GetBorder(TableBorderType borderType)
- {
- // instance with default border values
- Border b = new Border();
-
- // Get the tblPr (table properties) element for this Table,
- // null will be return if no such element exists.
- XElement tblPr = Xml.Element(XName.Get("tblPr", DocX.w.NamespaceName));
- if (tblPr == null)
- {
- // uses default border style
- }
-
- /*
- * Get the tblBorders (table borders) element for this Table,
- * null will be return if no such element exists.
- */
- XElement tblBorders = tblPr.Element(XName.Get("tblBorders", DocX.w.NamespaceName));
- if (tblBorders == null)
- {
- // uses default border style
- }
-
- /*
- * Get the 'borderType' (table border) element for this Table,
- * null will be return if no such element exists.
- */
- var tbordertype = borderType.ToString();
- // only lower the first char of string (because of insideH and insideV)
- tbordertype = tbordertype.Substring(0, 1).ToLower() + tbordertype.Substring(1);
-
- XElement tblBorderType = tblBorders.Element(XName.Get(tbordertype, DocX.w.NamespaceName));
- if (tblBorderType == null)
- {
- // uses default border style
- }
-
- // The val attribute is used for the border style
- XAttribute val = tblBorderType.Attribute(XName.Get("val", DocX.w.NamespaceName));
- // If val is null, this table contains no border information.
- if (val == null)
- {
- // uses default border style
- }
- else
- {
- try
- {
- string bordertype = "Tcbs_" + val.Value;
- b.Tcbs = (BorderStyle)Enum.Parse(typeof(BorderStyle), bordertype);
- }
- catch
- {
- val.Remove();
- // uses default border style
- }
- }
-
- // The sz attribute is used for the border size
- XAttribute sz = tblBorderType.Attribute(XName.Get("sz", DocX.w.NamespaceName));
- // If sz is null, this border contains no size information.
- if (sz == null)
- {
- // uses default border style
- }
- else
- {
- // If sz is not an int, something is wrong with this attributes value, so remove it
- int numerical_size;
- if (!int.TryParse(sz.Value, out numerical_size))
- sz.Remove();
- else
- {
- switch (numerical_size)
- {
- case 2: b.Size = BorderSize.one; break;
- case 4: b.Size = BorderSize.two; break;
- case 6: b.Size = BorderSize.three; break;
- case 8: b.Size = BorderSize.four; break;
- case 12: b.Size = BorderSize.five; break;
- case 18: b.Size = BorderSize.six; break;
- case 24: b.Size = BorderSize.seven; break;
- case 36: b.Size = BorderSize.eight; break;
- case 48: b.Size = BorderSize.nine; break;
- default: b.Size = BorderSize.one; break;
- }
- }
- }
-
- // The space attribute is used for the border spacing (probably '0')
- XAttribute space = tblBorderType.Attribute(XName.Get("space", DocX.w.NamespaceName));
- // If space is null, this border contains no space information.
- if (space == null)
- {
- // uses default border style
- }
- else
- {
- // If space is not an int, something is wrong with this attributes value, so remove it
- int borderspace;
- if (!int.TryParse(space.Value, out borderspace))
- {
- space.Remove();
- // uses default border style
- }
- else
- {
- b.Space = borderspace;
- }
- }
-
- // The color attribute is used for the border color
- XAttribute color = tblBorderType.Attribute(XName.Get("color", DocX.w.NamespaceName));
- if (color == null)
- {
- // uses default border style
- }
- else
- {
- // If color is not a Color, something is wrong with this attributes value, so remove it
- try
- {
- b.Color = ColorTranslator.FromHtml(string.Format("#{0}", color.Value));
- }
- catch
- {
- color.Remove();
- // uses default border style
- }
- }
- return b;
- }
-
- }
-
- /// <summary>
- /// Represents a single row in a Table.
- /// </summary>
- public class Row : Container
- {
- /// <summary>
- /// Calculates columns count in the row, taking spanned cells into account
- /// </summary>
- public Int32 ColumnCount
- {
- get
- {
- int gridSpanSum = 0;
-
- gridSpanSum += gridAfter;
-
- // Foreach each Cell between startIndex and endIndex inclusive.
- foreach (Cell c in Cells)
- {
- if (c.GridSpan != 0)
- {
- gridSpanSum += c.GridSpan - 1;
- }
- }
-
- // return cells count + count of spanned cells
- return Cells.Count + gridSpanSum;
- }
- }
-
- /// <summary>
- /// Returns the GridAfter of a row ie. The amount of cells that are deleted
- /// </summary>
- public int gridAfter
- {
- get
- {
- var gridAfterValue = 0;
- var trPr = Xml.Element(XName.Get("trPr", DocX.w.NamespaceName));
- if (trPr != null)
- {
- var gridAfter = trPr.Element(XName.Get("gridAfter", DocX.w.NamespaceName));
- var val = gridAfter?.Attribute(XName.Get("val", DocX.w.NamespaceName));
- if (val != null)
- {
- gridAfterValue += int.Parse(val.Value);
- }
- }
- return gridAfterValue;
- }
- }
-
- /// <summary>
- /// A list of Cells in this Row.
- /// </summary>
- public List<Cell> Cells
- {
- get
- {
- List<Cell> cells =
- (
- from c in Xml.Elements(XName.Get("tc", DocX.w.NamespaceName))
- select new Cell(this, Document, c)
- ).ToList();
-
- return cells;
- }
- }
-
- public void Remove()
- {
- XElement table = Xml.Parent;
-
- Xml.Remove();
- if (!table.Elements(XName.Get("tr", DocX.w.NamespaceName)).Any())
- table.Remove();
- }
-
- public override ReadOnlyCollection<Paragraph> Paragraphs
- {
- get
- {
- List<Paragraph> paragraphs =
- (
- from p in Xml.Descendants(DocX.w + "p")
- select new Paragraph(Document, p, 0)
- ).ToList();
-
- foreach (Paragraph p in paragraphs)
- p.PackagePart = table.mainPart;
-
- return paragraphs.AsReadOnly();
- }
- }
-
- internal Table table;
- internal Row(Table table, DocX document, XElement xml)
- : base(document, xml)
- {
- this.table = table;
- this.mainPart = table.mainPart;
- }
-
- /// <summary>
- /// The property name to set when specifiying an exact height
- /// </summary>
- /// <created>Nick Kusters</created>
- const string _hRule_Exact = "exact";
- /// <summary>
- /// The property name to set when specifying a minimum height
- /// </summary>
- /// <created>Nick Kusters</created>
- const string _hRule_AtLeast = "atLeast";
- /// <summary>
- /// Height in pixels. // Added by Joel, refactored by Cathal.
- /// </summary>
- public double Height
- {
- get
- {
- // Get the trPr (table row properties) element for this Row,
- // null will be return if no such element exists.
- XElement trPr = Xml.Element(XName.Get("trPr", DocX.w.NamespaceName));
-
- // If trPr is null, this row contains no height information.
- // Get the trHeight element for this Row,
- // null will be return if no such element exists.
- XElement trHeight = trPr?.Element(XName.Get("trHeight", DocX.w.NamespaceName));
-
- // If trHeight is null, this row contains no height information.
- // Get the val attribute for this trHeight element.
- XAttribute val = trHeight?.Attribute(XName.Get("val", DocX.w.NamespaceName));
-
- // If w is null, this cell contains no width information.
- if (val == null)
- return double.NaN;
-
- // If val is not a double, something is wrong with this attributes value, so remove it and return double.NaN;
- double heightInWordUnits;
- if (!double.TryParse(val.Value, out heightInWordUnits))
- {
- val.Remove();
- return double.NaN;
- }
-
- // 15 "word units" in one pixel
- return (heightInWordUnits / 15);
- }
- set
- {
- SetHeight(value, true);
- }
- }
- /// <summary>
- /// Helper method to set either the exact height or the min-height
- /// </summary>
- /// <param name="height">The height value to set (in pixels)</param>
- /// <param name="exact">
- /// If true, the height will be forced.
- /// If false, it will be treated as a minimum height, auto growing past it if need be.
- /// </param>
- /// <created>Nick Kusters</created>
- void SetHeight(double height, bool exact)
- {
- /*
- * Get the trPr (table row properties) element for this Row,
- * null will be return if no such element exists.
- */
- XElement trPr = Xml.Element(XName.Get("trPr", DocX.w.NamespaceName));
- if (trPr == null)
- {
- Xml.SetElementValue(XName.Get("trPr", DocX.w.NamespaceName), string.Empty);
- trPr = Xml.Element(XName.Get("trPr", DocX.w.NamespaceName));
-
- // Swapping trPr and tc elements - making trPr the first
- XElement tc = Xml.Element( XName.Get( "tc", DocX.w.NamespaceName ) );
- if( tc != null )
- {
- trPr.Remove();
- tc.AddBeforeSelf( trPr );
- }
- }
-
- /*
- * Get the trHeight element for this Row,
- * null will be return if no such element exists.
- */
- XElement trHeight = trPr.Element(XName.Get("trHeight", DocX.w.NamespaceName));
- if (trHeight == null)
- {
- trPr.SetElementValue(XName.Get("trHeight", DocX.w.NamespaceName), string.Empty);
- trHeight = trPr.Element(XName.Get("trHeight", DocX.w.NamespaceName));
- }
-
- // The hRule attribute needs to be set to exact.
- trHeight.SetAttributeValue(XName.Get("hRule", DocX.w.NamespaceName), exact ? _hRule_Exact : _hRule_AtLeast);
-
- // 15 "word units" is equal to one pixel.
- trHeight.SetAttributeValue(XName.Get("val", DocX.w.NamespaceName),
- ((int)(Math.Round(height * 15,0))).ToString( CultureInfo.InvariantCulture )); // national separators anf fraction should be avoided
- }
- /// <summary>
- /// Min-Height in pixels. // Added by Nick Kusters.
- /// </summary>
- /// <remarks>
- /// Value will be treated as a minimum height, auto growing past it if need be.
- /// </remarks>
- /// <created>Nick Kusters</created>
- public double MinHeight
- {
- get
- {
- // Just return the value from the normal height property since it doesn't care if you've set an exact or minimum height.
- return Height;
- }
- set
- {
- SetHeight(value, false);
- }
- }
-
-
- /// <summary>
- /// Set to true to make this row the table header row that will be repeated on each page
- /// </summary>
- public bool TableHeader
- {
- get
- {
- XElement trPr = Xml.Element(XName.Get("trPr", DocX.w.NamespaceName));
- if (trPr == null)
- return false;
- XElement tblHeader = trPr.Element(XName.Get("tblHeader", DocX.w.NamespaceName));
- return tblHeader != null;
- }
- set
- {
- XElement trPr = Xml.Element(XName.Get("trPr", DocX.w.NamespaceName));
- if (trPr == null)
- {
- Xml.SetElementValue(XName.Get("trPr", DocX.w.NamespaceName), string.Empty);
- trPr = Xml.Element(XName.Get("trPr", DocX.w.NamespaceName));
- }
- XElement tblHeader = trPr.Element(XName.Get("tblHeader", DocX.w.NamespaceName));
- if (tblHeader == null && value)
- {
- trPr.SetElementValue(XName.Get("tblHeader", DocX.w.NamespaceName), string.Empty);
- }
- if (tblHeader != null && !value)
- {
- tblHeader.Remove();
- }
- }
- }
-
-
- /// <summary>
- /// Allow row to break across pages.
- /// The default value is true: Word will break the contents of the row across pages.
- /// If set to false, the contents of the row will not be split across pages, the entire row will be moved to the next page instead.
- /// </summary>
- public bool BreakAcrossPages
- {
- get
- {
- XElement trPr = Xml.Element(XName.Get("trPr", DocX.w.NamespaceName));
-
- XElement trCantSplit = trPr?.Element(XName.Get("cantSplit", DocX.w.NamespaceName));
-
- return trCantSplit == null;
- }
-
- set
- {
- if (value == false)
- {
- XElement trPr = Xml.Element(XName.Get("trPr", DocX.w.NamespaceName));
- if (trPr == null)
- {
- Xml.SetElementValue(XName.Get("trPr", DocX.w.NamespaceName), string.Empty);
- trPr = Xml.Element(XName.Get("trPr", DocX.w.NamespaceName));
- }
-
- XElement trCantSplit = trPr.Element(XName.Get("cantSplit", DocX.w.NamespaceName));
- if (trCantSplit == null)
- trPr.SetElementValue(XName.Get("cantSplit", DocX.w.NamespaceName), string.Empty);
- }
- else
- {
- XElement trPr = Xml.Element(XName.Get("trPr", DocX.w.NamespaceName));
- XElement trCantSplit = trPr?.Element(XName.Get("cantSplit", DocX.w.NamespaceName));
- trCantSplit?.Remove();
- }
- }
- }
-
- /// <summary>
- /// Merge cells starting with startIndex and ending with endIndex.
- /// </summary>
- public void MergeCells(int startIndex, int endIndex)
- {
- // Check for valid start and end indexes.
- if (startIndex < 0 || endIndex <= startIndex || endIndex > Cells.Count + 1)
- throw new IndexOutOfRangeException();
-
- // The sum of all merged gridSpans.
- int gridSpanSum = 0;
-
- // Foreach each Cell between startIndex and endIndex inclusive.
- foreach (Cell c in Cells.Where((z, i) => i > startIndex && i <= endIndex))
- {
- XElement tcPr = c.Xml.Element(XName.Get("tcPr", DocX.w.NamespaceName));
- XElement gridSpan = tcPr?.Element(XName.Get("gridSpan", DocX.w.NamespaceName));
- if (gridSpan != null)
- {
- XAttribute val = gridSpan.Attribute(XName.Get("val", DocX.w.NamespaceName));
-
- int value;
- if (val != null && int.TryParse(val.Value, out value))
- gridSpanSum += value - 1;
- }
-
- // Add this cells Pragraph to the merge start Cell.
- Cells[startIndex].Xml.Add(c.Xml.Elements(XName.Get("p", DocX.w.NamespaceName)));
-
- // Remove this Cell.
- c.Xml.Remove();
- }
-
- /*
- * Get the tcPr (table cell properties) element for the first cell in this merge,
- * null will be returned if no such element exists.
- */
- XElement start_tcPr = Cells[startIndex].Xml.Element(XName.Get("tcPr", DocX.w.NamespaceName));
- if (start_tcPr == null)
- {
- Cells[startIndex].Xml.SetElementValue(XName.Get("tcPr", DocX.w.NamespaceName), string.Empty);
- start_tcPr = Cells[startIndex].Xml.Element(XName.Get("tcPr", DocX.w.NamespaceName));
- }
-
- /*
- * Get the gridSpan element of this row,
- * null will be returned if no such element exists.
- */
- XElement start_gridSpan = start_tcPr.Element(XName.Get("gridSpan", DocX.w.NamespaceName));
- if (start_gridSpan == null)
- {
- start_tcPr.SetElementValue(XName.Get("gridSpan", DocX.w.NamespaceName), string.Empty);
- start_gridSpan = start_tcPr.Element(XName.Get("gridSpan", DocX.w.NamespaceName));
- }
-
- /*
- * Get the val attribute of this row,
- * null will be returned if no such element exists.
- */
- XAttribute start_val = start_gridSpan.Attribute(XName.Get("val", DocX.w.NamespaceName));
-
- int start_value = 0;
- if (start_val != null)
- if (int.TryParse(start_val.Value, out start_value))
- gridSpanSum += start_value - 1;
-
- // Set the val attribute to the number of merged cells.
- start_gridSpan.SetAttributeValue(XName.Get("val", DocX.w.NamespaceName), (gridSpanSum + (endIndex - startIndex + 1)).ToString());
- }
- }
-
- public class Cell : Container
- {
- internal Row row;
-
- internal Cell(Row row, DocX document, XElement xml)
- : base(document, xml)
- {
- this.row = row;
- this.mainPart = row.mainPart;
- }
-
- public override ReadOnlyCollection<Paragraph> Paragraphs
- {
- get
- {
- ReadOnlyCollection<Paragraph> paragraphs = base.Paragraphs;
-
- foreach (Paragraph p in paragraphs)
- p.PackagePart = row.table.mainPart;
-
- return paragraphs;
- }
- }
- /// <summary>
- /// Returns the GridSpan of a specific Cell ie. How many cells are merged
- /// </summary>
- public int GridSpan
- {
- get
- {
- var gridSpanVal = 0;
- XElement tcPr = Xml.Element(XName.Get("tcPr", DocX.w.NamespaceName));
- XElement gridSpan = tcPr?.Element(XName.Get("gridSpan", DocX.w.NamespaceName));
- if (gridSpan != null)
- {
- XAttribute val = gridSpan.Attribute(XName.Get("val", DocX.w.NamespaceName));
-
- int value;
- if (val != null && int.TryParse(val.Value, out value))
- gridSpanVal = value;
- }
- return gridSpanVal;
- }
- }
-
- /// <summary>
- /// Gets or Sets this Cells vertical alignment.
- /// </summary>
- /// <!--Patch 7398 added by lckuiper on Nov 16th 2010 @ 2:23 PM-->
- /// <example>
- /// Creates a table with 3 cells and sets the vertical alignment of each to 1 of the 3 available options.
- /// <code>
- /// // Create a new document.
- ///using(DocX document = DocX.Create("Test.docx"))
- ///{
- /// // Insert a Table into this document.
- /// Table t = document.InsertTable(3, 1);
- ///
- /// // Set the design of the Table such that we can easily identify cell boundaries.
- /// t.Design = TableDesign.TableGrid;
- ///
- /// // Set the height of the row bigger than default.
- /// // We need to be able to see the difference in vertical cell alignment options.
- /// t.Rows[0].Height = 100;
- ///
- /// // Set the vertical alignment of cell0 to top.
- /// Cell c0 = t.Rows[0].Cells[0];
- /// c0.InsertParagraph("VerticalAlignment.Top");
- /// c0.VerticalAlignment = VerticalAlignment.Top;
- ///
- /// // Set the vertical alignment of cell1 to center.
- /// Cell c1 = t.Rows[0].Cells[1];
- /// c1.InsertParagraph("VerticalAlignment.Center");
- /// c1.VerticalAlignment = VerticalAlignment.Center;
- ///
- /// // Set the vertical alignment of cell2 to bottom.
- /// Cell c2 = t.Rows[0].Cells[2];
- /// c2.InsertParagraph("VerticalAlignment.Bottom");
- /// c2.VerticalAlignment = VerticalAlignment.Bottom;
- ///
- /// // Save the document.
- /// document.Save();
- ///}
- /// </code>
- /// </example>
- public VerticalAlignment VerticalAlignment
- {
- get
- {
- /*
- * Get the tcPr (table cell properties) element for this Cell,
- * null will be return if no such element exists.
- */
- XElement tcPr = Xml.Element(XName.Get("tcPr", DocX.w.NamespaceName));
-
- // If tcPr is null, this cell contains no width information.
- // Get the vAlign (table cell vertical alignment) element for this Cell,
- // null will be return if no such element exists.
- XElement vAlign = tcPr?.Element(XName.Get("vAlign", DocX.w.NamespaceName));
-
- // If vAlign is null, this cell contains no vertical alignment information.
- // Get the val attribute of the vAlign element.
- XAttribute val = vAlign?.Attribute(XName.Get("val", DocX.w.NamespaceName));
-
- // If val is null, this cell contains no vAlign information.
- if (val == null)
- return VerticalAlignment.Center;
-
- // If val is not a VerticalAlign enum, something is wrong with this attributes value, so remove it and return VerticalAlignment.Center;
- try
- {
- return (VerticalAlignment)Enum.Parse(typeof(VerticalAlignment), val.Value, true);
- }
-
- catch
- {
- val.Remove();
- return VerticalAlignment.Center;
- }
- }
-
- set
- {
- // Get the tcPr (table cell properties) element for this Cell,
- // null will be return if no such element exists.
- XElement tcPr = Xml.Element(XName.Get("tcPr", DocX.w.NamespaceName));
- if (tcPr == null)
- {
- Xml.SetElementValue(XName.Get("tcPr", DocX.w.NamespaceName), string.Empty);
- tcPr = Xml.Element(XName.Get("tcPr", DocX.w.NamespaceName));
- }
-
-
- // Get the vAlign (table cell vertical alignment) element for this Cell,
- // null will be return if no such element exists.
- XElement vAlign = tcPr.Element(XName.Get("vAlign", DocX.w.NamespaceName));
- if (vAlign == null)
- {
- tcPr.SetElementValue(XName.Get("vAlign", DocX.w.NamespaceName), string.Empty);
- vAlign = tcPr.Element(XName.Get("vAlign", DocX.w.NamespaceName));
- }
-
- // Set the VerticalAlignment in 'val'
- vAlign.SetAttributeValue(XName.Get("val", DocX.w.NamespaceName), value.ToString().ToLower());
- }
- }
-
- public Color Shading
- {
- get
- {
- // Get the tcPr (table cell properties) element for this Cell,
- // null will be return if no such element exists.
- XElement tcPr = Xml.Element(XName.Get("tcPr", DocX.w.NamespaceName));
-
- // If tcPr is null, this cell contains no Color information.
- // Get the shd (table shade) element for this Cell,
- // null will be return if no such element exists.
- XElement shd = tcPr?.Element(XName.Get("shd", DocX.w.NamespaceName));
-
- // If shd is null, this cell contains no Color information.
- // Get the w attribute of the tcW element.
- XAttribute fill = shd?.Attribute(XName.Get("fill", DocX.w.NamespaceName));
-
- // If fill is null, this cell contains no Color information.
- if (fill == null)
- return Color.White;
-
- return ColorTranslator.FromHtml(string.Format("#{0}", fill.Value));
- }
-
- set
- {
- // Get the tcPr (table cell properties) element for this Cell,
- // null will be return if no such element exists.
- XElement tcPr = Xml.Element(XName.Get("tcPr", DocX.w.NamespaceName));
- if (tcPr == null)
- {
- Xml.SetElementValue(XName.Get("tcPr", DocX.w.NamespaceName), string.Empty);
- tcPr = Xml.Element(XName.Get("tcPr", DocX.w.NamespaceName));
- }
-
- /*
- * Get the shd (table shade) element for this Cell,
- * null will be return if no such element exists.
- */
- XElement shd = tcPr.Element(XName.Get("shd", DocX.w.NamespaceName));
- if (shd == null)
- {
- tcPr.SetElementValue(XName.Get("shd", DocX.w.NamespaceName), string.Empty);
- shd = tcPr.Element(XName.Get("shd", DocX.w.NamespaceName));
- }
-
- // The val attribute needs to be set to clear
- shd.SetAttributeValue(XName.Get("val", DocX.w.NamespaceName), "clear");
-
- // The color attribute needs to be set to auto
- shd.SetAttributeValue(XName.Get("color", DocX.w.NamespaceName), "auto");
-
- // The fill attribute needs to be set to the hex for this Color.
- shd.SetAttributeValue(XName.Get("fill", DocX.w.NamespaceName), value.ToHex());
- }
- }
-
- /// <summary>
- /// Width in pixels. // Added by Joel, refactored by Cathal
- /// </summary>
- public double Width
- {
- get
- {
- // Get the tcPr (table cell properties) element for this Cell,
- // null will be return if no such element exists.
- XElement tcPr = Xml.Element(XName.Get("tcPr", DocX.w.NamespaceName));
-
- // If tcPr is null, this cell contains no width information.
- // Get the tcW (table cell width) element for this Cell,
- // null will be return if no such element exists.
- XElement tcW = tcPr?.Element(XName.Get("tcW", DocX.w.NamespaceName));
-
- // If tcW is null, this cell contains no width information.
- // Get the w attribute of the tcW element.
- XAttribute w = tcW?.Attribute(XName.Get("w", DocX.w.NamespaceName));
-
- // If w is null, this cell contains no width information.
- if (w == null)
- return double.NaN;
-
- // If w is not a double, something is wrong with this attributes value, so remove it and return double.NaN;
- double widthInWordUnits;
- if (!double.TryParse(w.Value, out widthInWordUnits))
- {
- w.Remove();
- return double.NaN;
- }
-
- // 15 "word units" is equal to one pixel.
- return (widthInWordUnits / 15);
- }
-
- set
- {
- /*
- * Get the tcPr (table cell properties) element for this Cell,
- * null will be return if no such element exists.
- */
- XElement tcPr = Xml.Element(XName.Get("tcPr", DocX.w.NamespaceName));
- if (tcPr == null)
- {
- Xml.SetElementValue(XName.Get("tcPr", DocX.w.NamespaceName), string.Empty);
- tcPr = Xml.Element(XName.Get("tcPr", DocX.w.NamespaceName));
- }
-
- /*
- * Get the tcW (table cell width) element for this Cell,
- * null will be return if no such element exists.
- */
- XElement tcW = tcPr.Element(XName.Get("tcW", DocX.w.NamespaceName));
- if (tcW == null)
- {
- tcPr.SetElementValue(XName.Get("tcW", DocX.w.NamespaceName), string.Empty);
- tcW = tcPr.Element(XName.Get("tcW", DocX.w.NamespaceName));
- }
-
- if (value == -1)
- {
- // remove cell width; due to set on table prop.
- tcW.Remove();
- return;
- }
-
- // 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.
- tcW.SetAttributeValue(XName.Get("type", DocX.w.NamespaceName), "dxa");
-
- // 15 "word units" is equal to one pixel.
- tcW.SetAttributeValue(XName.Get("w", DocX.w.NamespaceName), (value * 15).ToString());
- }
- }
-
- /// <summary>
- /// LeftMargin in pixels. // Added by lckuiper
- /// </summary>
- /// <example>
- /// <code>
- /// // Create a new document.
- ///using (DocX document = DocX.Create("Test.docx"))
- ///{
- /// // Insert table into this document.
- /// Table t = document.InsertTable(3, 3);
- /// t.Design = TableDesign.TableGrid;
- ///
- /// // Get the center cell.
- /// Cell center = t.Rows[1].Cells[1];
- ///
- /// // Insert some text so that we can see the effect of the Margins.
- /// center.Paragraphs[0].Append("Center Cell");
- ///
- /// // Set the center cells Left, Margin to 10.
- /// center.MarginLeft = 25;
- ///
- /// // Save the document.
- /// document.Save();
- ///}
- /// </code>
- /// </example>
- public double MarginLeft
- {
- get
- {
- /*
- * Get the tcPr (table cell properties) element for this Cell,
- * null will be return if no such element exists.
- */
- XElement tcPr = Xml.Element(XName.Get("tcPr", DocX.w.NamespaceName));
-
- // If tcPr is null, this cell contains no width information.
- if (tcPr == null)
- return double.NaN;
-
- /*
- * Get the tcMar
- *
- */
- XElement tcMar = tcPr.Element(XName.Get("tcMar", DocX.w.NamespaceName));
-
- // If tcMar is null, this cell contains no margin information.
- // Get the left (LeftMargin) element
- XElement tcMarLeft = tcMar?.Element(XName.Get("left", DocX.w.NamespaceName));
-
- // If tcMarLeft is null, this cell contains no left margin information.
- // Get the w attribute of the tcMarLeft element.
- XAttribute w = tcMarLeft?.Attribute(XName.Get("w", DocX.w.NamespaceName));
-
- // If w is null, this cell contains no width information.
- if (w == null)
- return double.NaN;
-
- // If w is not a double, something is wrong with this attributes value, so remove it and return double.NaN;
- double leftMarginInWordUnits;
- if (!double.TryParse(w.Value, out leftMarginInWordUnits))
- {
- w.Remove();
- return double.NaN;
- }
-
- // 15 "word units" is equal to one pixel.
- return (leftMarginInWordUnits / 15);
- }
-
- set
- {
- /*
- * Get the tcPr (table cell properties) element for this Cell,
- * null will be return if no such element exists.
- */
- XElement tcPr = Xml.Element(XName.Get("tcPr", DocX.w.NamespaceName));
- if (tcPr == null)
- {
- Xml.SetElementValue(XName.Get("tcPr", DocX.w.NamespaceName), string.Empty);
- tcPr = Xml.Element(XName.Get("tcPr", DocX.w.NamespaceName));
- }
-
- /*
- * Get the tcMar (table cell margin) element for this Cell,
- * null will be return if no such element exists.
- */
- XElement tcMar = tcPr.Element(XName.Get("tcMar", DocX.w.NamespaceName));
- if (tcMar == null)
- {
- tcPr.SetElementValue(XName.Get("tcMar", DocX.w.NamespaceName), string.Empty);
- tcMar = tcPr.Element(XName.Get("tcMar", DocX.w.NamespaceName));
- }
-
- /*
- * Get the left (table cell left margin) element for this Cell,
- * null will be return if no such element exists.
- */
- XElement tcMarLeft = tcMar.Element(XName.Get("left", DocX.w.NamespaceName));
- if (tcMarLeft == null)
- {
- tcMar.SetElementValue(XName.Get("left", DocX.w.NamespaceName), string.Empty);
- tcMarLeft = tcMar.Element(XName.Get("left", DocX.w.NamespaceName));
- }
-
- // 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.
- tcMarLeft.SetAttributeValue(XName.Get("type", DocX.w.NamespaceName), "dxa");
-
- // 15 "word units" is equal to one pixel.
- tcMarLeft.SetAttributeValue(XName.Get("w", DocX.w.NamespaceName), (value * 15).ToString());
- }
- }
-
- /// <summary>
- /// RightMargin in pixels. // Added by lckuiper
- /// </summary>
- /// <example>
- /// <code>
- /// // Create a new document.
- ///using (DocX document = DocX.Create("Test.docx"))
- ///{
- /// // Insert table into this document.
- /// Table t = document.InsertTable(3, 3);
- /// t.Design = TableDesign.TableGrid;
- ///
- /// // Get the center cell.
- /// Cell center = t.Rows[1].Cells[1];
- ///
- /// // Insert some text so that we can see the effect of the Margins.
- /// center.Paragraphs[0].Append("Center Cell");
- ///
- /// // Set the center cells Right, Margin to 10.
- /// center.MarginRight = 25;
- ///
- /// // Save the document.
- /// document.Save();
- ///}
- /// </code>
- /// </example>
- public double MarginRight
- {
- get
- {
- /*
- * Get the tcPr (table cell properties) element for this Cell,
- * null will be return if no such element exists.
- */
- XElement tcPr = Xml.Element(XName.Get("tcPr", DocX.w.NamespaceName));
-
- // If tcPr is null, this cell contains no width information.
- if (tcPr == null)
- return double.NaN;
-
- /*
- * Get the tcMar
- *
- */
- XElement tcMar = tcPr.Element(XName.Get("tcMar", DocX.w.NamespaceName));
-
- // If tcMar is null, this cell contains no margin information.
- // Get the right (RightMargin) element
- XElement tcMarRight = tcMar?.Element(XName.Get("right", DocX.w.NamespaceName));
-
- // If tcMarRight is null, this cell contains no right margin information.
- // Get the w attribute of the tcMarRight element.
- XAttribute w = tcMarRight?.Attribute(XName.Get("w", DocX.w.NamespaceName));
-
- // If w is null, this cell contains no width information.
- if (w == null)
- return double.NaN;
-
- // If w is not a double, something is wrong with this attributes value, so remove it and return double.NaN;
- double rightMarginInWordUnits;
- if (!double.TryParse(w.Value, out rightMarginInWordUnits))
- {
- w.Remove();
- return double.NaN;
- }
-
- // 15 "word units" is equal to one pixel.
- return (rightMarginInWordUnits / 15);
- }
-
- set
- {
- /*
- * Get the tcPr (table cell properties) element for this Cell,
- * null will be return if no such element exists.
- */
- XElement tcPr = Xml.Element(XName.Get("tcPr", DocX.w.NamespaceName));
- if (tcPr == null)
- {
- Xml.SetElementValue(XName.Get("tcPr", DocX.w.NamespaceName), string.Empty);
- tcPr = Xml.Element(XName.Get("tcPr", DocX.w.NamespaceName));
- }
-
- /*
- * Get the tcMar (table cell margin) element for this Cell,
- * null will be return if no such element exists.
- */
- XElement tcMar = tcPr.Element(XName.Get("tcMar", DocX.w.NamespaceName));
- if (tcMar == null)
- {
- tcPr.SetElementValue(XName.Get("tcMar", DocX.w.NamespaceName), string.Empty);
- tcMar = tcPr.Element(XName.Get("tcMar", DocX.w.NamespaceName));
- }
-
- /*
- * Get the right (table cell right margin) element for this Cell,
- * null will be return if no such element exists.
- */
- XElement tcMarRight = tcMar.Element(XName.Get("right", DocX.w.NamespaceName));
- if (tcMarRight == null)
- {
- tcMar.SetElementValue(XName.Get("right", DocX.w.NamespaceName), string.Empty);
- tcMarRight = tcMar.Element(XName.Get("right", DocX.w.NamespaceName));
- }
-
- // 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.
- tcMarRight.SetAttributeValue(XName.Get("type", DocX.w.NamespaceName), "dxa");
-
- // 15 "word units" is equal to one pixel.
- tcMarRight.SetAttributeValue(XName.Get("w", DocX.w.NamespaceName), (value * 15).ToString());
- }
- }
-
- /// <summary>
- /// TopMargin in pixels. // Added by lckuiper
- /// </summary>
- /// <example>
- /// <code>
- /// // Create a new document.
- ///using (DocX document = DocX.Create("Test.docx"))
- ///{
- /// // Insert table into this document.
- /// Table t = document.InsertTable(3, 3);
- /// t.Design = TableDesign.TableGrid;
- ///
- /// // Get the center cell.
- /// Cell center = t.Rows[1].Cells[1];
- ///
- /// // Insert some text so that we can see the effect of the Margins.
- /// center.Paragraphs[0].Append("Center Cell");
- ///
- /// // Set the center cells Top, Margin to 10.
- /// center.MarginTop = 25;
- ///
- /// // Save the document.
- /// document.Save();
- ///}
- /// </code>
- /// </example>
- public double MarginTop
- {
- get
- {
- /*
- * Get the tcPr (table cell properties) element for this Cell,
- * null will be return if no such element exists.
- */
- XElement tcPr = Xml.Element(XName.Get("tcPr", DocX.w.NamespaceName));
-
- // If tcPr is null, this cell contains no width information.
- if (tcPr == null)
- return double.NaN;
-
- /*
- * Get the tcMar
- *
- */
- XElement tcMar = tcPr.Element(XName.Get("tcMar", DocX.w.NamespaceName));
-
- // If tcMar is null, this cell contains no margin information.
- // Get the top (TopMargin) element
- XElement tcMarTop = tcMar?.Element(XName.Get("top", DocX.w.NamespaceName));
-
- // If tcMarTop is null, this cell contains no top margin information.
- // Get the w attribute of the tcMarTop element.
- XAttribute w = tcMarTop?.Attribute(XName.Get("w", DocX.w.NamespaceName));
-
- // If w is null, this cell contains no width information.
- if (w == null)
- return double.NaN;
-
- // If w is not a double, something is wrong with this attributes value, so remove it and return double.NaN;
- double topMarginInWordUnits;
- if (!double.TryParse(w.Value, out topMarginInWordUnits))
- {
- w.Remove();
- return double.NaN;
- }
-
- // 15 "word units" is equal to one pixel.
- return (topMarginInWordUnits / 15);
- }
-
- set
- {
- /*
- * Get the tcPr (table cell properties) element for this Cell,
- * null will be return if no such element exists.
- */
- XElement tcPr = Xml.Element(XName.Get("tcPr", DocX.w.NamespaceName));
- if (tcPr == null)
- {
- Xml.SetElementValue(XName.Get("tcPr", DocX.w.NamespaceName), string.Empty);
- tcPr = Xml.Element(XName.Get("tcPr", DocX.w.NamespaceName));
- }
-
- /*
- * Get the tcMar (table cell margin) element for this Cell,
- * null will be return if no such element exists.
- */
- XElement tcMar = tcPr.Element(XName.Get("tcMar", DocX.w.NamespaceName));
- if (tcMar == null)
- {
- tcPr.SetElementValue(XName.Get("tcMar", DocX.w.NamespaceName), string.Empty);
- tcMar = tcPr.Element(XName.Get("tcMar", DocX.w.NamespaceName));
- }
-
- /*
- * Get the top (table cell top margin) element for this Cell,
- * null will be return if no such element exists.
- */
- XElement tcMarTop = tcMar.Element(XName.Get("top", DocX.w.NamespaceName));
- if (tcMarTop == null)
- {
- tcMar.SetElementValue(XName.Get("top", DocX.w.NamespaceName), string.Empty);
- tcMarTop = tcMar.Element(XName.Get("top", DocX.w.NamespaceName));
- }
-
- // 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.
- tcMarTop.SetAttributeValue(XName.Get("type", DocX.w.NamespaceName), "dxa");
-
- // 15 "word units" is equal to one pixel.
- tcMarTop.SetAttributeValue(XName.Get("w", DocX.w.NamespaceName), (value * 15).ToString());
- }
- }
-
- /// <summary>
- /// BottomMargin in pixels. // Added by lckuiper
- /// </summary>
- /// <example>
- /// <code>
- /// // Create a new document.
- ///using (DocX document = DocX.Create("Test.docx"))
- ///{
- /// // Insert table into this document.
- /// Table t = document.InsertTable(3, 3);
- /// t.Design = TableDesign.TableGrid;
- ///
- /// // Get the center cell.
- /// Cell center = t.Rows[1].Cells[1];
- ///
- /// // Insert some text so that we can see the effect of the Margins.
- /// center.Paragraphs[0].Append("Center Cell");
- ///
- /// // Set the center cells Top, Margin to 10.
- /// center.MarginBottom = 25;
- ///
- /// // Save the document.
- /// document.Save();
- ///}
- /// </code>
- /// </example>
- public double MarginBottom
- {
- get
- {
- /*
- * Get the tcPr (table cell properties) element for this Cell,
- * null will be return if no such element exists.
- */
- XElement tcPr = Xml.Element(XName.Get("tcPr", DocX.w.NamespaceName));
-
- // If tcPr is null, this cell contains no width information.
-
- /*
- * Get the tcMar
- *
- */
- XElement tcMar = tcPr?.Element(XName.Get("tcMar", DocX.w.NamespaceName));
-
- // If tcMar is null, this cell contains no margin information.
- if (tcMar == null)
- return double.NaN;
-
- // Get the bottom (BottomMargin) element
- XElement tcMarBottom = tcMar.Element(XName.Get("bottom", DocX.w.NamespaceName));
-
- // If tcMarBottom is null, this cell contains no bottom margin information.
-
- // Get the w attribute of the tcMarBottom element.
- XAttribute w = tcMarBottom?.Attribute(XName.Get("w", DocX.w.NamespaceName));
-
- // If w is null, this cell contains no width information.
- if (w == null)
- return double.NaN;
-
- // If w is not a double, something is wrong with this attributes value, so remove it and return double.NaN;
- double bottomMarginInWordUnits;
- if (!double.TryParse(w.Value, out bottomMarginInWordUnits))
- {
- w.Remove();
- return double.NaN;
- }
-
- // 15 "word units" is equal to one pixel.
- return (bottomMarginInWordUnits / 15);
- }
-
- set
- {
- /*
- * Get the tcPr (table cell properties) element for this Cell,
- * null will be return if no such element exists.
- */
- XElement tcPr = Xml.Element(XName.Get("tcPr", DocX.w.NamespaceName));
- if (tcPr == null)
- {
- Xml.SetElementValue(XName.Get("tcPr", DocX.w.NamespaceName), string.Empty);
- tcPr = Xml.Element(XName.Get("tcPr", DocX.w.NamespaceName));
- }
-
- /*
- * Get the tcMar (table cell margin) element for this Cell,
- * null will be return if no such element exists.
- */
- XElement tcMar = tcPr.Element(XName.Get("tcMar", DocX.w.NamespaceName));
- if (tcMar == null)
- {
- tcPr.SetElementValue(XName.Get("tcMar", DocX.w.NamespaceName), string.Empty);
- tcMar = tcPr.Element(XName.Get("tcMar", DocX.w.NamespaceName));
- }
-
- /*
- * Get the bottom (table cell bottom margin) element for this Cell,
- * null will be return if no such element exists.
- */
- XElement tcMarBottom = tcMar.Element(XName.Get("bottom", DocX.w.NamespaceName));
- if (tcMarBottom == null)
- {
- tcMar.SetElementValue(XName.Get("bottom", DocX.w.NamespaceName), string.Empty);
- tcMarBottom = tcMar.Element(XName.Get("bottom", DocX.w.NamespaceName));
- }
-
- // 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.
- tcMarBottom.SetAttributeValue(XName.Get("type", DocX.w.NamespaceName), "dxa");
-
- // 15 "word units" is equal to one pixel.
- tcMarBottom.SetAttributeValue(XName.Get("w", DocX.w.NamespaceName), (value * 15).ToString());
- }
- }
-
- /// <summary>
- /// Set the table cell border
- /// Added by lckuiper @ 20101117
- /// </summary>
- /// <example>
- /// <code>
- /// // Create a new document.
- ///using (DocX document = DocX.Create("Test.docx"))
- ///{
- /// // Insert a table into this document.
- /// Table t = document.InsertTable(3, 3);
- ///
- /// // Get the center cell.
- /// Cell center = t.Rows[1].Cells[1];
- ///
- /// // Create a large blue border.
- /// Border b = new Border(BorderStyle.Tcbs_single, BorderSize.seven, 0, Color.Blue);
- ///
- /// // Set the center cells Top, Bottom, Left and Right Borders to b.
- /// center.SetBorder(TableCellBorderType.Top, b);
- /// center.SetBorder(TableCellBorderType.Bottom, b);
- /// center.SetBorder(TableCellBorderType.Left, b);
- /// center.SetBorder(TableCellBorderType.Right, b);
- ///
- /// // Save the document.
- /// document.Save();
- ///}
- /// </code>
- /// </example>
- /// <param name="borderType">Table Cell border to set</param>
- /// <param name="border">Border object to set the table cell border</param>
- public void SetBorder(TableCellBorderType borderType, Border border)
- {
- /*
- * Get the tcPr (table cell properties) element for this Cell,
- * null will be return if no such element exists.
- */
- XElement tcPr = Xml.Element(XName.Get("tcPr", DocX.w.NamespaceName));
- if (tcPr == null)
- {
- Xml.SetElementValue(XName.Get("tcPr", DocX.w.NamespaceName), string.Empty);
- tcPr = Xml.Element(XName.Get("tcPr", DocX.w.NamespaceName));
- }
-
- /*
- * Get the tblBorders (table cell borders) element for this Cell,
- * null will be return if no such element exists.
- */
- XElement tcBorders = tcPr.Element(XName.Get("tcBorders", DocX.w.NamespaceName));
- if (tcBorders == null)
- {
- tcPr.SetElementValue(XName.Get("tcBorders", DocX.w.NamespaceName), string.Empty);
- tcBorders = tcPr.Element(XName.Get("tcBorders", DocX.w.NamespaceName));
- }
-
- /*
- * Get the 'borderType' (table cell border) element for this Cell,
- * null will be return if no such element exists.
- */
- string tcbordertype;
- switch (borderType)
- {
- case TableCellBorderType.TopLeftToBottomRight:
- tcbordertype = "tl2br";
- break;
- case TableCellBorderType.TopRightToBottomLeft:
- tcbordertype = "tr2bl";
- break;
- default:
- // enum to string
- tcbordertype = borderType.ToString();
- // only lower the first char of string (because of insideH and insideV)
- tcbordertype = tcbordertype.Substring(0, 1).ToLower() + tcbordertype.Substring(1);
- break;
- }
-
- XElement tcBorderType = tcBorders.Element(XName.Get(borderType.ToString(), DocX.w.NamespaceName));
- if (tcBorderType == null)
- {
- tcBorders.SetElementValue(XName.Get(tcbordertype, DocX.w.NamespaceName), string.Empty);
- tcBorderType = tcBorders.Element(XName.Get(tcbordertype, DocX.w.NamespaceName));
- }
-
- // get string value of border style
- string borderstyle = border.Tcbs.ToString().Substring(5);
- borderstyle = borderstyle.Substring(0, 1).ToLower() + borderstyle.Substring(1);
-
- // The val attribute is used for the border style
- tcBorderType.SetAttributeValue(XName.Get("val", DocX.w.NamespaceName), borderstyle);
-
- int size;
- switch (border.Size)
- {
- case BorderSize.one: size = 2; break;
- case BorderSize.two: size = 4; break;
- case BorderSize.three: size = 6; break;
- case BorderSize.four: size = 8; break;
- case BorderSize.five: size = 12; break;
- case BorderSize.six: size = 18; break;
- case BorderSize.seven: size = 24; break;
- case BorderSize.eight: size = 36; break;
- case BorderSize.nine: size = 48; break;
- default: size = 2; break;
- }
-
- // The sz attribute is used for the border size
- tcBorderType.SetAttributeValue(XName.Get("sz", DocX.w.NamespaceName), (size).ToString());
-
- // The space attribute is used for the cell spacing (probably '0')
- tcBorderType.SetAttributeValue(XName.Get("space", DocX.w.NamespaceName), (border.Space).ToString());
-
- // The color attribute is used for the border color
- tcBorderType.SetAttributeValue(XName.Get("color", DocX.w.NamespaceName), border.Color.ToHex());
- }
-
-
- /// <summary>
- /// Get a table cell border
- /// Added by lckuiper @ 20101117
- /// </summary>
- /// <param name="borderType">The table cell border to get</param>
- public Border GetBorder(TableCellBorderType borderType)
- {
- // instance with default border values
- var b = new Border();
-
- /*
- * Get the tcPr (table cell properties) element for this Cell,
- * null will be return if no such element exists.
- */
- XElement tcPr = Xml.Element(XName.Get("tcPr", DocX.w.NamespaceName));
- if (tcPr == null)
- {
- // uses default border style
- }
-
- /*
- * Get the tcBorders (table cell borders) element for this Cell,
- * null will be return if no such element exists.
- */
- XElement tcBorders = tcPr.Element(XName.Get("tcBorders", DocX.w.NamespaceName));
- if (tcBorders == null)
- {
- // uses default border style
- }
-
- /*
- * Get the 'borderType' (cell border) element for this Cell,
- * null will be return if no such element exists.
- */
- var tcbordertype = borderType.ToString();
-
- switch (tcbordertype)
- {
- case "TopLeftToBottomRight":
- tcbordertype = "tl2br";
- break;
- case "TopRightToBottomLeft":
- tcbordertype = "tr2bl";
- break;
- default:
- // only lower the first char of string (because of insideH and insideV)
- tcbordertype = tcbordertype.Substring(0, 1).ToLower() + tcbordertype.Substring(1);
- break;
- }
-
- XElement tcBorderType = tcBorders.Element(XName.Get(tcbordertype, DocX.w.NamespaceName));
- if (tcBorderType == null)
- {
- // uses default border style
- }
-
- // The val attribute is used for the border style
- XAttribute val = tcBorderType.Attribute(XName.Get("val", DocX.w.NamespaceName));
- // If val is null, this cell contains no border information.
- if (val == null)
- {
- // uses default border style
- }
- else
- {
- try
- {
- string bordertype = "Tcbs_" + val.Value;
- b.Tcbs = (BorderStyle)Enum.Parse(typeof(BorderStyle), bordertype);
- }
-
- catch
- {
- val.Remove();
- // uses default border style
- }
- }
-
- // The sz attribute is used for the border size
- XAttribute sz = tcBorderType.Attribute(XName.Get("sz", DocX.w.NamespaceName));
- // If sz is null, this border contains no size information.
- if (sz == null)
- {
- // uses default border style
- }
- else
- {
- // If sz is not an int, something is wrong with this attributes value, so remove it
- int numerical_size;
- if (!int.TryParse(sz.Value, out numerical_size))
- sz.Remove();
- else
- {
- switch (numerical_size)
- {
- case 2: b.Size = BorderSize.one; break;
- case 4: b.Size = BorderSize.two; break;
- case 6: b.Size = BorderSize.three; break;
- case 8: b.Size = BorderSize.four; break;
- case 12: b.Size = BorderSize.five; break;
- case 18: b.Size = BorderSize.six; break;
- case 24: b.Size = BorderSize.seven; break;
- case 36: b.Size = BorderSize.eight; break;
- case 48: b.Size = BorderSize.nine; break;
- default: b.Size = BorderSize.one; break;
- }
- }
- }
-
- // The space attribute is used for the border spacing (probably '0')
- XAttribute space = tcBorderType.Attribute(XName.Get("space", DocX.w.NamespaceName));
- // If space is null, this border contains no space information.
- if (space == null)
- {
- // uses default border style
- }
- else
- {
- // If space is not an int, something is wrong with this attributes value, so remove it
- int borderspace;
- if (!int.TryParse(space.Value, out borderspace))
- {
- space.Remove();
- // uses default border style
- }
- else
- {
- b.Space = borderspace;
- }
- }
-
- // The color attribute is used for the border color
- XAttribute color = tcBorderType.Attribute(XName.Get("color", DocX.w.NamespaceName));
- if (color == null)
- {
- // uses default border style
- }
- else
- {
- // If color is not a Color, something is wrong with this attributes value, so remove it
- try
- {
- b.Color = ColorTranslator.FromHtml(string.Format("#{0}", color.Value));
- }
- catch
- {
- color.Remove();
- // uses default border style
- }
- }
- return b;
- }
-
- /// <summary>
- /// Gets or Sets the fill color of this Cell.
- /// </summary>
- /// <example>
- /// <code>
- /// // Create a new document.
- /// using (DocX document = DocX.Create("Test.docx"))
- /// {
- /// // Insert a table into this document.
- /// Table t = document.InsertTable(3, 3);
- ///
- /// // Fill the first cell as Blue.
- /// t.Rows[0].Cells[0].FillColor = Color.Blue;
- /// // Fill the middle cell as Red.
- /// t.Rows[1].Cells[1].FillColor = Color.Red;
- /// // Fill the last cell as Green.
- /// t.Rows[2].Cells[2].FillColor = Color.Green;
- ///
- /// // Save the document.
- /// document.Save();
- /// }
- /// </code>
- /// </example>
- public Color FillColor
- {
- get
- {
- /*
- * Get the tcPr (table cell properties) element for this Cell,
- * null will be return if no such element exists.
- */
- XElement tcPr = Xml.Element(XName.Get("tcPr", DocX.w.NamespaceName));
- XElement shd = tcPr?.Element(XName.Get("shd", DocX.w.NamespaceName));
- XAttribute fill = shd?.Attribute(XName.Get("fill", DocX.w.NamespaceName));
- if (fill == null)
- return Color.Empty;
- int argb = Int32.Parse(fill.Value.Replace("#", ""), NumberStyles.HexNumber);
- return Color.FromArgb(argb);
- }
-
- set
- {
- /*
- * Get the tcPr (table cell properties) element for this Cell,
- * null will be return if no such element exists.
- */
- XElement tcPr = Xml.Element(XName.Get("tcPr", DocX.w.NamespaceName));
- if (tcPr == null)
- {
- Xml.SetElementValue(XName.Get("tcPr", DocX.w.NamespaceName), string.Empty);
- tcPr = Xml.Element(XName.Get("tcPr", DocX.w.NamespaceName));
- }
-
- /*
- * Get the tcW (table cell width) element for this Cell,
- * null will be return if no such element exists.
- */
- XElement shd = tcPr.Element(XName.Get("shd", DocX.w.NamespaceName));
- if (shd == null)
- {
- tcPr.SetElementValue(XName.Get("shd", DocX.w.NamespaceName), string.Empty);
- shd = tcPr.Element(XName.Get("shd", DocX.w.NamespaceName));
- }
-
- shd.SetAttributeValue(XName.Get("val", DocX.w.NamespaceName), "clear");
- shd.SetAttributeValue(XName.Get("color", DocX.w.NamespaceName), "auto");
- shd.SetAttributeValue(XName.Get("fill", DocX.w.NamespaceName), value.ToHex());
- }
- }
-
- public override Table InsertTable(int rowCount, int columnCount)
- {
- Table table = base.InsertTable(rowCount, columnCount);
- table.mainPart = mainPart;
- InsertParagraph(); //Dmitchern, It is necessary to put paragraph in the end of the cell, without it MS-Word will say that the document is corrupted
- //IMPORTANT: It will be better to check all methods that work with adding anything to cells
- return table;
- }
-
- public TextDirection TextDirection
- {
- get
- {
- XElement tcPr = Xml.Element(XName.Get("tcPr", DocX.w.NamespaceName));
-
- // If tcPr is null, this cell contains no width information.
- XElement textDirection = tcPr?.Element(XName.Get("textDirection", DocX.w.NamespaceName));
- XAttribute val = textDirection?.Attribute(XName.Get("val", DocX.w.NamespaceName));
- if (val == null)
- return TextDirection.right;
-
- // If val is not a VerticalAlign enum, something is wrong with this attributes value, so remove it and return VerticalAlignment.Center;
- try
- {
- return (TextDirection)Enum.Parse(typeof(TextDirection), val.Value, true);
- }
- catch
- {
- val.Remove();
- return TextDirection.right;
- }
- }
- set
- {
- /*
- * Get the tcPr (table cell properties) element for this Cell,
- * null will be return if no such element exists.
- */
- XElement tcPr = Xml.Element(XName.Get("tcPr", DocX.w.NamespaceName));
- if (tcPr == null)
- {
- Xml.SetElementValue(XName.Get("tcPr", DocX.w.NamespaceName), string.Empty);
- tcPr = Xml.Element(XName.Get("tcPr", DocX.w.NamespaceName));
- }
-
- /*
- * Get the vAlign (table cell vertical alignment) element for this Cell,
- * null will be return if no such element exists.
- */
- XElement textDirection = tcPr.Element(XName.Get("textDirection", DocX.w.NamespaceName));
- if (textDirection == null)
- {
- tcPr.SetElementValue(XName.Get("textDirection", DocX.w.NamespaceName), string.Empty);
- textDirection = tcPr.Element(XName.Get("textDirection", DocX.w.NamespaceName));
- }
-
- // Set the VerticalAlignment in 'val'
- textDirection.SetAttributeValue(XName.Get("val", DocX.w.NamespaceName), value.ToString());
-
- }
- }
- }
-
-
- public class TableLook
- {
- public bool FirstRow { get; set; }
- public bool LastRow { get; set; }
- public bool FirstColumn { get; set; }
- public bool LastColumn { get; set; }
- public bool NoHorizontalBanding { get; set; }
- public bool NoVerticalBanding { get; set; }
- }
-
- }
|