If somebody like the post and its helpful in your work then, add comments.

Monday, October 26, 2009

New in InfoPath 2010

In InfoPath 2010, there are many changes. Like is UI or it controls etc. Now it is also have some changes in designing, data connection. Some good and new changes/feature which I find is listed below.

Products Changes:

  1. Rich ribbon interface with InfoPath 2010.

        InfoPath2010005

   2. There are two products in Microsoft 2010 officer.

Microsoft InfoPath Designer 2010: For designing the form. 

   InfoPath2010001

      Microsoft InfoPath Editor 2010: For form filling.

   InfoPath2010002

Microsoft InfoPath Designer 2010 Changes :

Data Connection:

1. There is increase in receive data connection.

    InfoPath2010003

2. Shorting in data connection

   InfoPath2010004

Addition in Controls:

1. In Web form we have following controls :

   InfoPath2010006

2. In Client form we have following controls:

   InfoPath2010007

3. Control properties is show in ribbon

  InfoPath2010008

4. Compatibility changes

  InfoPath2010009

5. Automatic versioning

   InfoPath2010010

6. Property Promotion

 InfoPath2010011

7. Rule enhancements

   InfoPath2010012

8. Addition of Context in formula

   InfoPath2010013

9. Single Publish button

   InfoPath2010014

Tuesday, September 29, 2009

Timed Jobs in SharePoint

Microsoft Windows SharePoint Services (WSS) and its Portal version, Microsoft Office SharePoint Server (MOSS), carries out various automatic, scheduled jobs to realize repetitive tasks in a standard way.

The SharePoint Timed Jobs infrastructure takes care of the scheduled tasks needed to ensure proper functioning of the system. Timed Jobs run in the background and are based in the Microsoft SharePoint Timer service, which is always installed in the default setup of WSS and MOSS. Installed Timed Jobs can be configured from SharePoint's Central Administration using the Command-Line administrator's tool or programmed using the Object Model.

Limitation

Timed Jobs can be set up to run immediately or in a time frame based on "one," meaning a SharePoint Job can run each minute, day, or week but not, for example, every two hours or days. Another limitation is that it is impossible to schedule Jobs to run on relative time frames; for example, the second Monday of every month. A Timed Job requires a starting time, and the configured time frame determines the interval it will run at. The starting time can be an absolute time (at 12:00 am, for example) or a time range (between 8:00 and 9:00 am); in the first instance, the Job would require a few seconds to execute because the service needs to be initiated; in the second case, the Job will run at a random time within the range, giving the different servers in the farm the opportunity to progress at varied periods, balancing the load on the system.

Friday, August 21, 2009

Updating the SharePoint User Profile in SSP Programmatically

The User Profile Database in SharePoint is a great centralized location for storing all the information about the users of your SharePoint Portal.

To import the AD profiles in SharePoint then we have use UserProfileConfigManager class.

Add following references in solution:

using Microsoft.SharePoint;
using
Microsoft.Office.Server.UserProfiles;
using
Microsoft.Office.Server;
using
System.Web;

and the following code


SPSite HomeSite = new SPSite("http://mossvs2008");

           UserProfileConfigManager SPUserProfileConfigManager = new UserProfileConfigManager(ServerContext.GetContext(HomeSite));

           if (SPUserProfileConfigManager.IsImportInProgress() == false)

               SPUserProfileConfigManager.StartImport(true);


Sunday, August 9, 2009

WordProcessingML : How to update Table of Content in MS Word Document

To update the Table of content in the Microsoft word document first we have 
to create a table of content in first of document. Then write below code to
update the table of content updation.
class Program 
{
public static XNamespace ns = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";

static void Main(string[] args)
{
using (WordprocessingDocument WorDocument = WordprocessingDocument.Create(@"C:\TestDocuments\TOCDocument.docx", WordprocessingDocumentType.Document))
{
// Add a new main document part.
MainDocumentPart mainPart = WorDocument.AddMainDocumentPart();
//Create Document tree for simple document.
mainPart.Document = new Document();
//Create Body (this element contains other elements that we want to include
Body body = new Body();

//Save changes to the main document part.
mainPart.Document.Append(body);

XDocument xmlXdocument = XDocument.Parse(mainPart.Document.InnerXml);
IEnumerable<XElement> xmlelement = xmlXdocument.Descendants(ns + "sdt");
XElement TOCRefNode = xmlelement.First();
GenerateTOC(xmlXdocument, TOCRefNode);

mainPart.Document.InnerXml = xmlXdocument.ToString();

mainPart.Document.Save();
WorDocument.Close();

}
}

#region TOC Creation

/// <summary>
///
returns title paragraphs of genereated doc fro creating toc hyperlink
/// </summary>
private static IEnumerable<XElement> TitleParagraphsElements(XDocument mainDocument)
{
IEnumerable<XElement> results = mainDocument.Descendants().Where
(
tag =>
tag.Name == ns + "p" &&
tag.Descendants(ns + "t").Count() > 0 &&
tag.Descendants().Where
(
tag2 =>
tag2.Name == ns + "pStyle" &&
(
tag2.Attribute(ns + "val").Value == "Head1" ||
tag2.Attribute(ns + "val").Value == "Head2" ||
tag2.Attribute(ns + "val").Value == "Head3" ||
tag2.Attribute(ns + "val").Value == "Head4" ||
tag2.Attribute(ns + "val").Value == "Head5" ||
tag2.Attribute(ns + "val").Value == "Head6"
)
).Count() > 0
);

return results;
}

private static void GenerateTOC(XDocument xmlMainDocument, XElement TOCRefNode)
{
int bookMarkIdCounter = 0;
int maxHeading = 1;
int tempheading = 1;

// sdtContent, will contain all the paragraphs used in the TOC
XElement sdtContent = new XElement(ns + "sdtContent");
String strContentHdr = "";
XElement xContentHdr = TOCRefNode.Elements(ns + "sdtContent").First().Descendants().Where(
tag =>
tag.Name == ns + "p" &&
tag.Descendants().Where
(
tag2 =>
tag2.Name == ns + "pStyle" &&
tag2.Attribute(ns + "val").Value == "TOCHeading"
).Count() > 0
).FirstOrDefault();

if (xContentHdr != null)
strContentHdr = xContentHdr.Descendants(ns + "t").FirstOrDefault().Value;

// some information regarding the attributes of the TOC
xContentHdr.Add(

new XElement(ns + "r",
new XElement(ns + "fldChar",
new XAttribute(ns + "fldCharType", "begin"))),
new XElement(ns + "r",
new XElement(ns + "instrText",
new XAttribute(XNamespace.Xml + "space", "preserve"),
"TOCLIMIT")),
new XElement(ns + "r",
new XElement(ns + "fldChar",
new XAttribute(ns + "fldCharType", "separate"))));
sdtContent.Add(new XElement(xContentHdr));


// for each title found it in the document, we have to wrap the run inside of it,
// with a bookmark, this bookmark will have an id which will work as an anchor,
// for link references in the TOC
foreach (XElement titleParagraph in TitleParagraphsElements(xmlMainDocument))
{
string bookmarkName = "_TOC" + bookMarkIdCounter;
XElement bookmarkStart =
new XElement(ns + "bookmarkStart",
new XAttribute(ns + "id", bookMarkIdCounter),
new XAttribute(ns + "name", bookmarkName));
XElement bookmarkEnd =
new XElement(ns + "bookmarkEnd",
new XAttribute(ns + "id", bookMarkIdCounter));

// wrap the run with bookmarkStart and bookmarkEnd
titleParagraph.AddFirst(bookmarkStart);
titleParagraph.Add(bookmarkEnd);

// get the name of the style of the parapgraph of the title, and for each one,
// choose a style to add in the paragraph inside the TOC
string referenceTitleStyle = "";
switch (titleParagraph.Descendants(ns + "pStyle").First().Attribute(ns + "val").Value)
{
case "Head1":
{
referenceTitleStyle = "TOC1";
tempheading = 1;
break;
}
case "Head2":
{
referenceTitleStyle = "TOC2";
tempheading = 2;
break;
}
case "Head3":
{
referenceTitleStyle = "TOC3";
tempheading = 3;
break;
}
case "Head4":
{
referenceTitleStyle = "TOC4";
tempheading = 4;
break;
}
case "Head5":
{
referenceTitleStyle = "TOC5";
tempheading = 5;
break;
}
case "Head6":
{
referenceTitleStyle = "TOC6";
tempheading = 6;
break;
}
}


string entryContent = "";
IEnumerable<XElement> owTList = titleParagraph.Descendants(ns + "t");
foreach (XElement entryElement in owTList)
{
entryContent += (entryElement == null ? string.Empty : entryElement.Value);
}

XElement TOCElement = null;
XElement tempTOCElement = TOCRefNode.Elements(ns + "sdtContent").First().Descendants().Where(
tag =>
tag.Name == ns + "p" &&
tag.Descendants().Where
(
tag2 =>
tag2.Name == ns + "pStyle" &&
tag2.Attribute(ns + "val").Value == referenceTitleStyle
).Count() > 0
).FirstOrDefault();

if (tempTOCElement != null)
{
if (maxHeading < tempheading)
maxHeading = tempheading;

TOCElement = new XElement(tempTOCElement);
//delete instrText which contains TOC 1-n
XElement instrTextTOC = TOCElement.Descendants().Where(
tag =>
tag.Name == ns + "r" &&
tag.Descendants().Where(
tag2 =>
tag2.Name == ns + "instrText" &&
tag2.Value.Contains(@"TOC \o ")
).Count() > 0

).FirstOrDefault();
if (instrTextTOC != null)
{
instrTextTOC.ElementsAfterSelf(ns + "r").Remove();
instrTextTOC.ElementsBeforeSelf(ns + "r").Remove();
instrTextTOC.Remove();
}

//get hyperlink node
XElement hyperlink = TOCElement.Descendants().Where(
tag =>
tag.Name == ns + "hyperlink"

).FirstOrDefault();
//update anchor attribute value
hyperlink.Attribute(ns + "anchor").Value = bookmarkName;

//get entry content node
XElement contentNode = hyperlink.Descendants().Where(
tag =>
tag.Name == ns + "r" &&
tag.Descendants().Where(
tag2 =>
tag2.Name == ns + "rStyle" &&
tag2.Attribute(ns + "val").Value == "Hyperlink"
).Count() > 0 &&
tag.Elements(ns + "t").Count() > 0

).FirstOrDefault().Elements(ns + "t").FirstOrDefault();

contentNode.Value = entryContent;

//update PAGEREF value
XElement instrText = TOCElement.Descendants().Where(
tag =>
tag.Name == ns + "instrText" &&
tag.Value.Contains("PAGEREF ")
).FirstOrDefault();
if (instrText != null)
{
instrText.Value = " PAGEREF " + bookmarkName + @" \h ";
}

sdtContent.Add(TOCElement);
bookMarkIdCounter++;
}


}

sdtContent.Descendants().Where(
tag =>
tag.Name == ns + "instrText"
&&
tag.Value.Contains("TOCLIMIT")
).FirstOrDefault().Value = String.Format(@"TOC \o ""1-{0}"" \h \z \u ", maxHeading);

sdtContent.Add(
new XElement(ns + "p",
new XElement(ns + "r",
new XElement(ns + "fldChar",
new XAttribute(ns + "fldCharType", "end")))));

// Finish the xml construction of the TOC
XElement TOC =
new XElement(ns + "sdt",
new XElement(ns + "sdtPr",
new XElement(ns + "docPartObj",
new XElement(ns + "docPartGallery",
new XAttribute(ns + "val", "Table of Contents")),
new XElement(ns + "docPartUnique"))),
sdtContent);

// add it to the original document
IEnumerable<XElement> tocNodes = xmlMainDocument.Descendants().Where
(
tag =>
tag.Name == ns + "sdt" &&
tag.Descendants(ns + "sdtContent").Count() > 0 &&
tag.Descendants().Where
(
tag2 =>
tag2.Name == ns + "p" &&
tag2.Descendants().Where
(
tag3 =>
tag3.Name == ns + "pStyle" &&
(
tag3.Attribute(ns + "val").Value == "TOCHeading"
)
).Count() > 0

).Count() > 0
);

TOCRefNode.ReplaceWith(TOC);

}

#endregion
Solution is provided by open xmldeveloper.org at following
link

Download Solution

Thursday, August 6, 2009

WordprocessingML : Insert page number in the word document in center bottom of MS Word Document

Their are 3 things required for the inserting page number;

1. Footer.xml
2. Footnotes.xml
3. EndNotes.xml

And Section Properties to append in the document.

Sample code for that

                Footer footer = new Footer(new Paragraph(new ParagraphProperties(new ParagraphStyleId() { Val = "Footer" })));
                var footerPart1 = mainPart.AddNewPart<FooterPart>("rid110");
                Footer1().Save(footerPart1);
                body.Append(footer);

                Footnotes footnotes = new Footnotes(new Paragraph(new ParagraphProperties(new ParagraphStyleId() { Val = "Footnotes" })));
                var footnodeinpage = mainPart.AddNewPart<FootnotesPart>("rid111");
                PageFootNote().Save(footnodeinpage);
                body.Append(footnotes);

                Endnotes endnotes = new Endnotes(new Paragraph(new ParagraphProperties(new ParagraphStyleId() { Val = "Endnotes" })));
                var endnodeinpage = mainPart.AddNewPart<EndnotesPart>("rid112");
                PageEndNote().Save(endnodeinpage);
                body.Append(endnotes);

                body.Append(PageSectionProperties());


Methods

#region Page Number
private static Endnotes PageEndNote()
{
var element =
new Endnotes(
new Endnote(
new Paragraph(
new ParagraphProperties(
new SpacingBetweenLines() { After = (UInt64Value)0UL, Line = 240, LineRule = LineSpacingRuleValues.Auto }),
new Run(
new SeparatorMark())
) { RsidParagraphAddition = "00670250", RsidParagraphProperties = "00EA1D8B", RsidRunAdditionDefault = "00670250" }
) { Type = FootnoteEndnoteValues.Separator, Id = 0 },
new Endnote(
new Paragraph(
new ParagraphProperties(
new SpacingBetweenLines() { After = (UInt64Value)0UL, Line = 240, LineRule = LineSpacingRuleValues.Auto }),
new Run(
new ContinuationSeparatorMark())
) { RsidParagraphAddition = "00670250", RsidParagraphProperties = "00EA1D8B", RsidRunAdditionDefault = "00670250" }
) { Type = FootnoteEndnoteValues.ContinuationSeparator, Id = 1 });
return element;
}

private static Footer Footer1()
{
var element =
new Footer(
new SdtBlock(
new SdtProperties(
new SdtId() { Val = 538536024 },
new DocPartObjectSdt(
new DocPartGallery() { Val = "Page Numbers (Bottom of Page)" },
new DocPartUnique())),
new SdtContentBlock(
new Paragraph(
new ParagraphProperties(
new ParagraphStyleId() { Val = "Footer" },
new Justification() { Val = JustificationValues.Center }),
new SimpleField(
new Run(
new RunProperties(
new NoProof()),
new Text("6") ->Total Page Number in document
) { RsidRunAddition = "00E906EE" }
) { Instruction = " PAGE \\* MERGEFORMAT " }
) { RsidParagraphAddition = "00EA1D8B", RsidRunAdditionDefault = "002E7045" })),
new Paragraph(
new ParagraphProperties(
new ParagraphStyleId() { Val = "Footer" })
) { RsidParagraphAddition = "00EA1D8B", RsidRunAdditionDefault = "00EA1D8B" });
return element;
}

private static Footnotes PageFootNote()
{
var element =
new Footnotes(
new Footnote(
new Paragraph(
new ParagraphProperties(
new SpacingBetweenLines() { After = (UInt64Value)0UL, Line = 240, LineRule = LineSpacingRuleValues.Auto }),
new Run(
new SeparatorMark())
) { RsidParagraphAddition = "00670250", RsidParagraphProperties = "00EA1D8B", RsidRunAdditionDefault = "00670250" }
) { Type = FootnoteEndnoteValues.Separator, Id = 0 },
new Footnote(
new Paragraph(
new ParagraphProperties(
new SpacingBetweenLines() { After = (UInt64Value)0UL, Line = 240, LineRule = LineSpacingRuleValues.Auto }),
new Run(
new ContinuationSeparatorMark())
) { RsidParagraphAddition = "00670250", RsidParagraphProperties = "00EA1D8B", RsidRunAdditionDefault = "00670250" }
) { Type = FootnoteEndnoteValues.ContinuationSeparator, Id = 1 });
return element;
}

//Adding the section properties in the document
public static SectionProperties PageSectionProperties()
{
var element =
new SectionProperties(
new FooterReference() { Type = HeaderFooterValues.Default, Id = "rid110" },
new PageSize() { Width = (UInt64Value)12240UL, Height = (UInt64Value)15840UL },
new PageMargin() { Top = 1440, Right = (UInt64Value)1440UL, Bottom = 1440, Left = (UInt64Value)1440UL, Header = (UInt64Value)720UL, Footer = (UInt64Value)720UL, Gutter = (UInt64Value)0UL },
new Columns() { Space = (UInt64Value)720UL },
new DocGrid() { LinePitch = 360 }
) { RsidRPr = "007024C7", RsidR = "000B6998", RsidSect = "006040EE" };
return element;
}

#endregion

Also find on openxmldeveloper.org Link

Monday, August 3, 2009

SpreadsheetML: Updating a range in the Excel Sheet

The below code update the cell rane in the excel sheet.

#region Approch 1

#region Calculate Sum of Cell Range

private static void CalculateSumOfCellRange(string docName, string worksheetName, string resultCell)
{
// Open the document for editing.
using (SpreadsheetDocument document = SpreadsheetDocument.Open(docName, true))
{
IEnumerable sheets = document.WorkbookPart.Workbook.Descendants().Where(s => s.Name == worksheetName);
if (sheets.Count() == 0)
{
// The specified worksheet does not exist.
return;
}

WorksheetPart worksheetPart = (WorksheetPart)document.WorkbookPart.GetPartById(sheets.First().Id);
Worksheet worksheet = worksheetPart.Worksheet;

#region Insert Cell Values
Cell result1 = InsertCellInWorksheet(GetColumnName("B4"), GetRowIndex(resultCell), worksheetPart);
Cell result2 = InsertCellInWorksheet(GetColumnName("C4"), GetRowIndex(resultCell), worksheetPart);
Cell result3 = InsertCellInWorksheet(GetColumnName("D4"), GetRowIndex(resultCell), worksheetPart);
Cell result4 = InsertCellInWorksheet(GetColumnName("E4"), GetRowIndex(resultCell), worksheetPart);
Cell result5 = InsertCellInWorksheet(GetColumnName("F4"), GetRowIndex(resultCell), worksheetPart);
Cell result6 = InsertCellInWorksheet(GetColumnName("G4"), GetRowIndex(resultCell), worksheetPart);
Cell resultSum = InsertCellInWorksheet(GetColumnName("J4"), GetRowIndex(resultCell), worksheetPart);

result1.DataType = new EnumValue(CellValues.Number);
result1.CellValue = new CellValue("1000");

result1.DataType = new EnumValue(CellValues.Number);
result1.CellValue = new CellValue("20000");

result2.DataType = new EnumValue(CellValues.Number);
result2.CellValue = new CellValue("100000");

result3.DataType = new EnumValue(CellValues.Number);
result3.CellValue = new CellValue("145000");

result4.DataType = new EnumValue(CellValues.Number);
result4.CellValue = new CellValue("301200000");

result5.DataType = new EnumValue(CellValues.Number);
result5.CellValue = new CellValue("440000");

result6.DataType = new EnumValue(CellValues.Number);
result6.CellValue = new CellValue("400000");

resultSum.CellFormula = new CellFormula("=sum(B4:G4)");
#endregion


worksheetPart.Worksheet.Save();
document.Close();
}
}

#endregion

#region Get Row Index in Sheet
// Given a cell name, parses the specified cell to get the row index.
private static uint GetRowIndex(string cellName)
{
// Create a regular expression to match the row index portion the cell name.
Regex regex = new Regex(@"\d+");
Match match = regex.Match(cellName);

return uint.Parse(match.Value);
}

#endregion

#region Get Column Name in Sheet
// Given a cell name, parses the specified cell to get the column name.
private static string GetColumnName(string cellName)
{
// Create a regular expression to match the column name portion of the cell name.
Regex regex = new Regex("[A-Za-z]+");
Match match = regex.Match(cellName);

return match.Value;
}

#endregion

#region Insert a Cell into a Worksheet
// Given a column name, a row index, and a WorksheetPart, inserts a cell into the worksheet.
// If the cell already exists, returns it.
private static Cell InsertCellInWorksheet(string columnName, uint rowIndex, WorksheetPart worksheetPart)
{
Worksheet worksheet = worksheetPart.Worksheet;
SheetData sheetData = worksheet.GetFirstChild();
string cellReference = columnName + rowIndex;

// If the worksheet does not contain a row with the specified row index, insert one.
Row row;
if (sheetData.Elements().Where(r => r.RowIndex == rowIndex).Count() != 0)
{
row = sheetData.Elements().Where(r => r.RowIndex == rowIndex).First();
}
else
{
row = new Row() { RowIndex = rowIndex };
sheetData.Append(row);
}

// If there is not a cell with the specified column name, insert one.
if (row.Elements().Where(c => c.CellReference.Value == columnName + rowIndex).Count() > 0)
{
return row.Elements().Where(c => c.CellReference.Value == cellReference).First();
}
else
{
// Cells must be in sequential order according to CellReference. Determine where to insert the new cell.
Cell refCell = null;
foreach (Cell cell in row.Elements())
{
if (string.Compare(cell.CellReference.Value, cellReference, true) > 0)
{
refCell = cell;
break;
}
}

Cell newCell = new Cell() { CellReference = cellReference };
row.InsertBefore(newCell, refCell);

worksheet.Save();
return newCell;
}
}
#endregion

#endregion

I leverage the msdn link for to update cell range in the excel sheet.

Monday, July 27, 2009

SpredSheetML : Updating Column in Excel sheet

Hi,

Thw basic thing in excel is to update the cell in the sheet. We have know idea how to do that. From packaging class method it is diffcult/complez to update specific row column. The SPreadsheetML makes more easy to do that. We have to just add reference of the DocumentFormat.OpenXml and write below code in the solution.

Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml;

namespace ExcelUpdation
{
class Program
{
static void Main(string[] args)
{
// InsertText(@"c:\SummaryGraphs.xlsx", "123456789");
UpdateCell(@"c:\SummaryGraphs.xlsx", "420", 22, "C");
UpdateCell(@"c:\SummaryGraphs.xlsx", "420", 22, "D");
UpdateCell(@"c:\SummaryGraphs.xlsx", "420", 22, "E");
UpdateCell(@"c:\SummaryGraphs.xlsx", "420", 22, "F");
UpdateCell(@"c:\SummaryGraphs.xlsx", "420", 22, "G");
UpdateCell(@"c:\SummaryGraphs.xlsx", "420", 22, "H");

UpdateCell(@"c:\SummaryGraphs.xlsx", "421", 23, "C");
UpdateCell(@"c:\SummaryGraphs.xlsx", "421", 23, "D");
UpdateCell(@"c:\SummaryGraphs.xlsx", "421", 23, "E");
UpdateCell(@"c:\SummaryGraphs.xlsx", "421", 23, "F");
UpdateCell(@"c:\SummaryGraphs.xlsx", "421", 23, "G");
UpdateCell(@"c:\SummaryGraphs.xlsx", "421", 23, "H");


}

#region Approch 1

public static void UpdateCell(string docName, string text,uint rowIndex, string columnName)
{
// Open the document for editing.
using (SpreadsheetDocument spreadSheet = SpreadsheetDocument.Open(docName, true))
{
WorksheetPart worksheetPart = GetWorksheetPartByName(spreadSheet, "Summary"); //Sheet Title in work book
if (worksheetPart != null)
{ Cell cell = GetCell(worksheetPart.Worksheet, columnName, rowIndex);
cell.CellValue = new CellValue(text);
cell.DataType = new EnumValue(CellValues.Number);
// Save the worksheet.
worksheetPart.Worksheet.Save();
}
}
}
private static WorksheetPart GetWorksheetPartByName(SpreadsheetDocument document, string sheetName)
{
IEnumerable sheets = document.WorkbookPart.Workbook.GetFirstChild(). Elements().Where(s => s.Name == sheetName);
if (sheets.Count() == 0)
{
// The specified worksheet does not exist.
return null;
}
string relationshipId = sheets.First().Id.Value;
WorksheetPart worksheetPart = (WorksheetPart)
document.WorkbookPart.GetPartById(relationshipId);
return worksheetPart;
}
// Given a worksheet, a column name, and a row index,
// gets the cell at the specified column and
private static Cell GetCell(Worksheet worksheet, string columnName, uint rowIndex)
{
Row row = GetRow(worksheet, rowIndex);
if (row == null)
return null;
return row.Elements().Where(c => string.Compare (c.CellReference.Value, columnName +
rowIndex, true) == 0).First();
}
// Given a worksheet and a row index, return the row.
private static Row GetRow(Worksheet worksheet, uint rowIndex)
{
return worksheet.GetFirstChild().
Elements().Where(r => r.RowIndex == rowIndex).First();
}
#endregion

}
}

The reference link
Click Here!

Friday, July 17, 2009

Open XML : Retrieving Word Content Based on Styles

To find or retrive content style based conetent from created word document:

Follow this code:

public static string paraStyle = "Heading1";
public static string paraStyle2 = "Heading2";

using (WordprocessingDocument WorDocument = WordprocessingDocument.Create(@"c:\Test.docx", WordprocessingDocumentType.Document))
{
// Add a new main document part.
MainDocumentPart mainPart = WorDocument.AddMainDocumentPart();
//Create Document tree for simple document.
mainPart.Document = new Document();
//Create Body (this element contains other elements that we want to include
Body body = new Body();
mainPart.Document.Append(body);
// Save changes to the main document part.
mainPart.Document.Save();


int countHeading1= mainPart.ParagraphsByStyleName(paraStyle).Count();
int countHeading2 = mainPart.ParagraphsByStyleName(paraStyle2).Count();
}
}


//Content Serch code.

#region Content

public static string GetStyleIdFromStyleName(MainDocumentPart mainPart, string styleName)
{
StyleDefinitionsPart stylePart = mainPart.StyleDefinitionsPart;
string styleId = stylePart.Styles.Descendants <StyleId >().Where
(s = > s.Val.Value.Equals(styleName))
.Select(n = > ((Style)n.Parent).StyleId).FirstOrDefault();
return styleId ?? styleName;
}
public static IEnumerable <Paragraph > ParagraphsByStyleName(this MainDocumentPart mainPart, string styleName)
{
string styleId = GetStyleIdFromStyleName(mainPart, styleName);
IEnumerable <Paragraph > paraList =
mainPart.Document.Descendants <Paragraph >()
.Where(p = > IsParagraphInStyle(p, styleId));
return paraList;
}

private static bool IsParagraphInStyle(Paragraph p, string styleId)
{
ParagraphProperties pPr = p.GetFirstChild <ParagraphProperties >();
if (pPr != null)
{
ParagraphStyleId paraStyle = pPr.ParagraphStyleId;
if (paraStyle != null)
{
return paraStyle.Val.Value.Equals(styleId);
}
}
return false;
}
public static IEnumerable <Run > RunsByStyleName(this MainDocumentPart mainPart, string styleName)
{
string styleId = GetStyleIdFromStyleName(mainPart, styleName);
IEnumerable <Run > runList = mainPart.Document.Descendants <Run >()
.Where(r = > IsRunInStyle(r, styleId));
return runList;
}
private static bool IsRunInStyle(Run r, string styleId)
{
RunProperties rPr = r.GetFirstChild <RunProperties >();
if (rPr != null)
{
RunStyleId runStyle = rPr.RunStyleId;
if (runStyle != null)
{
return runStyle.Val.Value.Equals(styleId);
}
}
return false;
}
//For Table style
public static IEnumerable <Table > TablesByStyleName(this MainDocumentPart mainPart, string styleName)
{
string styleId = GetStyleIdFromStyleName(mainPart, styleName);
IEnumerable <Table > tableList = mainPart.Document.Descendants <Table >()
.Where(t = > IsTableInStyle(t, styleId));
return tableList;
}
private static bool IsTableInStyle(Table tbl, string styleId)
{
TableProperties tblPr = tbl.GetFirstChild <TableProperties >();
if (tblPr != null)
{
TableStyleId tblStyle = tblPr.TableStyleId;
if (tblStyle != null)
{
return tblStyle.Val.Value.Equals(styleId);
}
}
return false;
}

#endregion

Thursday, July 16, 2009

Open XML: How to use Reflector Tool in Open XML SDK 2.0

This brief description show how to use the documentreflector tool for open xml sdk 2.0.

1. Create a sample document to insert text programmatically like below in screen:


2. Open the tool from SDK folder tools.


3. Click on DocumentReflector Tool.


4. It opens as below in the screen.


5. Click on file->open


6. Select created document from the dialog box.



7. The tools show all the related xml from the document.


8. Click on Document-body-paragraph-text


9. Click on Paragraph.

10 Click on File->Export Code


11. Save the CS file


12. Export Success message


13. The genrated CS file. use in your code.