Quantcast
Channel: Open XML Format SDK forum
Viewing all 1288 articles
Browse latest View live

Mail Merge field with formated value cannot be replaced with same formmated

$
0
0

HHow to replace the below xml with value "current date" and that should be return the result with the formatted value mentioned"dddd, MMMM dd, yyyy".

<w:fldSimple w:instr="MERGEFIELD CurrentDate \@ "dddd, MMMM dd, yyyy"">

-<w:r w:rsidR="00963793">
-<w:rPr>
 <w:noProof/>
 </w:rPr>
 <w:t>«CurrentDate»</w:t>
 </w:r>
 </w:fldSimple>

</w:p>

I have replaced the value for current date by using the code.But the current date is not displayed in the format"dddd, MMMM dd, yyyy". 

  if (fldSimples != null)
  {
          for (int i = (fldSimples.Length) - 1; i >= 0; i--)
           {
               SimpleField fldSimple = fldSimples[i];
               fldContent = fldSimple.InnerText.ToString();
               fldContent = fldContent.Substring(1, fldContent.Length - 2);
               xmlvalue = XMLdoc.SelectSingleNode(@"//LETTERDATA/" + fldContent);
               fldContent = xmlvalue.FirstChild.InnerText;
               fieldList += fldContent;
                             
               Run r = (Run)fldSimple.Elements<Run>().FirstOrDefault().CloneNode(true);
               r.Descendants<Text>().FirstOrDefault().Text = fldContent;
               fldSimple.PreviousSibling().Append(r);
               fldSimple.RemoveAllChildren();
               fldSimple.Remove();
           }
      }


Create word 2010 document (.docx) from a Mail Merge Template (.dotx) using OpenXML in VS2012

$
0
0

Hi

I need to create a Word 2010 document from Word 2010 Templates using OpenXML, VS 2012, C#.

I have created a word 2010 template (.dotx) using a SQL view and kept that template in the Server, now I need to create document based on the database record(s) from the client application (Window application or web application - need both facility)

Can anyone tell all the steps involved here also sample code or any links would be helpful?

one more question, whenever I open the template , a warning message shown that “Opening this document will run the following sql”

If I create a document from the template using OpenXml, Will that message be shown when user opens the generated document?  

Regards

MSK


Excel OpenXML - select ranges

$
0
0

Hi,

I'm using OpenXML SDK to parse Excel files. I want to select an area using openxml like I would if I had excel open and used CTRL Shift Arrow Down + Arrow Right. Is that possible using openxml or would I have to implement the logic myself?

Thanks.

Mail Merge fields are not displayed as framed in the word template (.dot) file with formated and formula field...

$
0
0
I have created a word template and insert four mailmerge fields,

1) current date with formula field.
{MERGEFIELD  CurrentDate /@ "dddd, MMMM dd, yyyy "}

2)Patientsex with IF--else condition formula
Formula like this
{IF {MERGEFIELD "PatientSex"} ="Male" "1" "2"}

3)Username with UPPERCASE

{MERGEFIELD  UserName \* Upper}

4)patientSurname with normal field

When toggle field code the four merge fields looks like this

{MERGEFIELD PatientSurname}

{MERGEFIELD  UserName \* Upper}

{MERGEFIELD  CurrentDate \@ "MMMM d, yyyy"}

{IF{MERGEFIELD PatientSex} = "Male" "1" "2"}

By using word object in VB code the mailmerge process happens with following method

bjMSWord.MailMergeOpenDataSource

bjMSWord.MailMergeToDoc

,We merge the document and replaced the merge field value from a text file

The text file having the value for merge fields as follow

1)currentdate (16th December 2013)

2)PatientSex (Male)

3)userName (Administrative User)

4)PatientSurname(sam)

After mail merge done the document displays output with merged values

1)currentdate (December 1, 2013)

2)PatientSex (1)

3)userName (ADMINISTRATIVE USER)

4)PatientSurname(sam)

By using word object,the value was replaced as format which has been mentioned in word templete.the word 

taking care of it.

I am trying to do the same process by using OPENXML wihout using Word object because the word object is not 

working properly in window serverside for (WINDOWS 8 OS).

I created a template with the merge files mentioned in the below .
By using open xml i have extracts the merge field using pacakage and replace the value form diferent xml 

file.the value has been replaced and the document will open with the newly repalced value.
But it is working fine for normal values.For formmated and formula fields it is not working properly.

If it is possible to do the process by using OPENXML.

Using OpenXml i replaced the value in the XML but the fields displayed the value as like normal fields.Here 

word does not do the format as done through word object.

The output word file displayed like this

1)currentdate (16th December 2013)

2)PatientSex (Male)

3)userName (Administrative User)

4)PatientSurname(sam)

Please inform whether it is possible or any better way to handle the formula field and formatted value and 

formula fields to replace mailmerge fields.

PowerPoint Slide with C# Specify Slide Layout

$
0
0

Using the sample code linked at the bottom from Microsoft I have the following code after adding a new slide to a presentation:

            // Use the same slide layout as that of the previous slide.            if (null != lastSlidePart.SlideLayoutPart) {                slidePart.AddPart(lastSlidePart.SlideLayoutPart);            }

It is not working.  The lastSlidePart definitely has the SlideLayoutPart I am looking for with 4 shapes in the shapetree, but the added slide (slidePart) only has 2 shapes in the shapetree.

I was using the following code as an example:

http://msdn.microsoft.com/en-us/library/cc850834(v=office.14).aspx

How to convert .docx file to html file with formatting using open xml sdk 2.5

$
0
0

HI,

I am trying to convert the document file(.docx) to html file. Currently I am able to do the conversion but html file does not retain the formatting.  I am using open xml sdk 2.0.

For example: If a paragraph contain the text in red color with some text with bold and underline in docx file, the converted html shows all the lines as simple text and lost all the formatting. 

Here is my current code :

        public string ConvertDocxToHtml(string docxFileEncodedData)
        {
            string inputFileName = DateTime.Now.ToString("ddMMyyyyhhmmss") + ".docx";
            string imageDirectoryName = inputFileName.Split('.')[0] + "_files";

            DirectoryInfo imgDirInfo = new DirectoryInfo(HttpContext.Current.Server.MapPath("~/Documents/" + imageDirectoryName));

            int imageCounter = 0;
            byte[] byteArray = Convert.FromBase64String(docxFileEncodedData);//File.ReadAllBytes(docxFile);
            using (MemoryStream memoryStream = new MemoryStream())
            {
                memoryStream.Write(byteArray, 0, byteArray.Length);
                using (WordprocessingDocument doc =
                    WordprocessingDocument.Open(memoryStream, true))
                {
                    HtmlConverterSettings settings = new HtmlConverterSettings()
                    {
                        PageTitle = inputFileName,
                        ConvertFormatting = false,
                    };
                    XElement html = HtmlConverter.ConvertToHtml(doc, settings,
                        imageInfo =>
                        {
                            DirectoryInfo localDirInfo = imgDirInfo;
                            if (!localDirInfo.Exists)
                                localDirInfo.Create();++imageCounter;
                            string extension = imageInfo.ContentType.Split('/')[1].ToLower();
                            ImageFormat imageFormat = null;
                            if (extension == "png")
                            {
                                // Convert the .png file to a .jpeg file.
                                extension = "jpeg";
                                imageFormat = ImageFormat.Jpeg;
                            }
                            else if (extension == "bmp")
                                imageFormat = ImageFormat.Bmp;
                            else if (extension == "jpeg")
                                imageFormat = ImageFormat.Jpeg;
                            else if (extension == "tiff")
                                imageFormat = ImageFormat.Tiff;

                            // If the image format is not one that you expect, ignore it,
                            // and do not return markup for the link.
                            if (imageFormat == null)
                                return null;

                            string imageFileName = "image" + imageCounter.ToString() + "." + extension;
                            try
                            {
                                imageInfo.Bitmap.Save(imgDirInfo.FullName + "/" + imageFileName, imageFormat);
                            }
                            catch (System.Runtime.InteropServices.ExternalException)
                            {
                                return null;
                            }
                            XElement img = new XElement(Xhtml.img,
                                new XAttribute(NoNamespace.src, imageDirectoryName + "/" + imageFileName),
                                imageInfo.ImgStyleAttribute,
                                imageInfo.AltText != null ?
                                    new XAttribute(NoNamespace.alt, imageInfo.AltText) : null);
                            return img;
                        });

                    string htmlFilePath = HttpContext.Current.Server.MapPath("~/Documents/" + inputFileName.Split('.')[0] + ".html");
                    File.WriteAllText(htmlFilePath, html.ToStringNewLineOnAttributes());

                    return ConfigurationManager.AppSettings["ServerUri"].ToString() + "/Documents/" + inputFileName.Split('.')[0] + ".html";
                }
            }

        }

So I just want to know how can I retain the format of docx in html file ?

Thanks

open xml for javascript excel sample code

$
0
0

hi,

I am trying to edit a  excel sheet in nodejs using open xml sdk for javascript. 

I found sample code very useful at http://openxmlsdkjs.codeplex.com/ but most of the code is related to Word file manipulation.

Can you please point me to any sample code or documentation for excel on similar lines.

Thanks,

Arun

Save word document as pdf

$
0
0

Hello,

Office 2007 installed and PDFConverter installed.
I opened word programmatically and when i try to save word file as pdf file as the following code i accept the following exception :

 

object oFileFormat= 17;// PDF
oPrintDoc.Application.Visible = false;
oPrintDoc.SaveAs(
ref oTmpPdfFile,ref oFileFormat,ref missingValue,
ref missingValue,ref missingValue,ref missingValue,
ref missingValue, ref missingValue,ref missingValue,
ref missingValue,ref missingValue,ref missingValue,ref missingValue,ref missingValue,ref missingValue,
ref missingValue);

System.Runtime.InteropServices.COMException (0x800A1066)

at Microsoft.Office.Interop.Word.DocumentClass.SaveAs(Object& FileName, Object& FileFormat, Object& LockComments, Object& Password, Object& AddToRecentFiles, Object& WritePassword, Object& ReadOnlyRecommended, Object& EmbedTrueTypeFonts, Object& SaveNativePictureFormat, Object& SaveFormsData, Object& SaveAsAOCELetter, Object& Encoding, Object& InsertLineBreaks, Object& AllowSubstitutions, Object& LineEnding, Object& AddBiDiMarks)

What is the problem ?

Thnx,
khalil


Inserting image with OpenXml 2.0, Error with contents in Word 2007

How to implement the feature that adjusts an Excel column to the precise width, programmatically??

$
0
0

My Open XML-based application creates a spreadsheet that contains a column with filenames. They vary in length and I would like to set the width of that particular column to precisely fit the longest filename.

Is there some Excel-specific way to measure the width of a string (with the current font, of course), in pixels?

TIA




how to handle section breaks

$
0
0

Hi ,

I am new to Office Open XML

in Word 2003 ml , each section is separated or consolidated within wx:sect element?

in word 2010's wordprocessingml we dont have any such element?

Do we have any other equivalent element for wx:sect in word 2010 wordml?

Or this is not required...???

How to handle Section breaks and heaer footer in this case.

How to remove a Section and the contents enclosed in that section

$
0
0

In Word 2003 , wx:sect was acting like a container for the section. So if i need to remove the content in that section , i simply remove the  wx:sect node in that section., I would need to apply same or similar concept in word 2010  Open xml also.

in my application we have coded in such a way that if a condition fails we will delete the section, which is ultimately we remove the <wx:sect> node.

But now since we have no w:sect node, though we remove the w:sectpr it is just removing the break but not the content in that section.

For example,

The template is

--- Section 1

case name : << >>

Date:  << >>      Sales name :      << >>                SalesID:  << >>

--- Section  2

Complaint Name : << >>    Order ID:  << >>  Product details : << >>

If New Order then the Section 2 must be deleted, if existing one Section 1 must be deleted.

previously if i removed  wx:sect node it would remove the content of that section also.

Now i would like to implement the same in word 2010 - Open XML also.

Kindly guide me on the same

Using Office Open XML File Formats to add web browser control in power point

$
0
0

Any reference on adding web browser control in power point using Office Open XML File formats ?

Thanks.

Excel: How to find the index of a Spreadsheet Column?

$
0
0

I am trying to determine the Style of each column, in order to apply it to the data that is inserted in each cell.

The confusing part is that instead of an index, the Column class provides a Min and a Max value. Sometimes they are the same, sometimes they are 1 unit apart.

Related Code:

Worksheet worksheet = worksheetPart.Worksheet;
Columns   columns   = worksheet.GetFirstChild<Columns>();

for (Column column = (Column) columns.FirstChild; column != null; column = (Column) column.NextSibling())
{
    UInt32 Style;

    if (column.Style == null)
    {
        Style = 0;
    }
    else
    {
        Style = column.Style.Value;
    }
    var Min = column.Min.Value;
    var Max = column.Max.Value;
    Console.WriteLine("Column Min=" + Min + ", Max=" + Max + ", Style: " + Style);
}

What is the deal with that Min-Max?

TIA

How to insert value in to particular cell in excel document which is created from template

$
0
0

Hi Team,

I need some help on inserting values in excel file using openxml.

I have tried with standard code which Microsoft giving to insert values in to excel. But if i am writing large files about 3000 rows and 50 columns it is taking more than 20 min.

I have found a workaround to insert excel values using OpenXMLWriter. 

But it is not working with the template approach. It is working only if i create new sheetdata and workseet.

And is there any way to insert value into particular cells using OpenXMLWriter.

The code i am using is

 WorkbookPart workbookpart = null;
            WorksheetPart worksheetpart = null;
            Worksheet worksheet = null;
            SheetData sheetdata = null;
            OpenXmlWriter writer = null;
            Cell cell = null;
            Row row = null;

           

            SpreadsheetDocumentObj.CompressionOption = CompressionOption.SuperFast;

            
            workbookpart = SpreadsheetDocumentObj.WorkbookPart;
            Sheet sheet = workbookpart.Workbook.Descendants<Sheet>().Where(

               (s) => s.Name == "Sheet1").FirstOrDefault();

            worksheetpart = (WorksheetPart)(workbookpart.GetPartById(sheet.Id));
            worksheet = worksheetpart.Worksheet;
            sheetdata = worksheet.GetFirstChild<SheetData>();

            writer = OpenXmlWriter.Create(worksheetpart);
            writer.WriteStartElement(new Worksheet(worksheet.OuterXml));
            writer.WriteStartElement(new SheetData(sheetdata.OuterXml));

           


            for (int i = 1; i < 35000; i++)
            {
                row = new Row();
                
                for (int j = 0; j < 100; j++)
                {

                    cell = new Cell();
                    cell.SetAttribute(new OpenXmlAttribute("", "t", "", "inlineStr"));
                    cell.InlineString = new InlineString { Text = new Text { Text = "Hi" } };
                    row.Append(cell);

                   
                }

                writer.WriteElement(row);
                
            }


            writer.WriteEndElement();
            writer.WriteEndElement();
            writer.Close();
            workbookpart.Workbook.Save();
            SpreadsheetDocumentObj.Close();

Please help me out of this. Any help is appreciated.

Thanks & Regards,

Programmer Kadapa


Programmer Kadapa


How to remove a Column? How about a Row?

$
0
0

How do we programmatically remove a Column in the same fashion as Excel would?

While we are in the topic: How to remove a Row?

TIA

How to delete a row in Excel file with Open Xml Sdk

$
0
0

Hi all,

I currently want to delete a row in excel file(not clear content) with Open Xml Sdk(

using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;

)

Any ideas?

Create or coping file creates a corrupted file or file with corrupted data. Using OpenXML 2.0

$
0
0

Hi,

Im using Document.OpenXML 2.0 for my project. The issue with my code is each time I create a file, when I open it I'm having corrupted file error and if I copy a file I couldn't open the file as well and getting error 'File having corrupted data.'

Following are my code for create file:

Dim docName As String = "C:\Testing" & DateTime.Now.ToString("yyyyMMdd") & ".ods"

        ' Create a Wordprocessing document. 
        Using package As WordprocessingDocument = WordprocessingDocument.Create(docName, WordprocessingDocumentType.Document)
            ' Add a new main document part. 
            package.AddMainDocumentPart()

            ' Create the Document DOM. 
            package.MainDocumentPart.Document = New DocumentFormat.OpenXml.Wordprocessing.Document(New DocumentFormat.OpenXml.Wordprocessing.Body(New DocumentFormat.OpenXml.Wordprocessing.Paragraph(New Run(New Text("Hello World!")))))

            ' Save changes to the main document part. 
            package.MainDocumentPart.Document.Save()
        End Using

This code successfully creates a file but when I open it, I get 'File corrupted' error. When I try to repair, I'm getting 'The file '$(ARG1)' could not be repaired and therefore cannot be opened' error.

This is are my code to copy file:

Dim extTemplate As String = "C:\Users\User\Desktop\StaffEvalForm\FinalAmendment.xls"
Dim StaffEvaluationReport As String = "C:\Users\User\Desktop\StaffEvalForm\StaffEvaluationReport" & DateTime.Now.ToString("yyyyMMdd") & ".xls"

File.Copy(extTemplate, StaffEvaluationReport, True) Using myWorkbook As SpreadsheetDocument = SpreadsheetDocument.Open(StaffEvaluationReport, False) Dim workbookPart As WorkbookPart = myWorkbook.WorkbookPart Dim WorksheetPart As WorksheetPart = workbookPart.WorksheetParts.First() Dim sheetData As SheetData = WorksheetPart.Worksheet.GetFirstChild(Of SheetData)() Dim index As Integer = 2 For Each objView_StaffEvalRow As DSHREval.HREvalRow In HREvalDALC.GetApprovedStaffEvaluationForm(FormStatus, Session(SharedCommon.UserName), Me.dtpStartDate.SelectedDate, Me.dtpEndDate.SelectedDate) Dim IDs As Integer = objView_StaffEvalRow.EmpID Dim EmpName As String = objView_StaffEvalRow.EmpName Dim contentRow As Row = CreateContentRow(index, IDs, EmpName) index += 1 sheetData.AppendChild(contentRow) Next End Using


This successfully copies the file but at line 

Using myWorkbook As SpreadsheetDocument = SpreadsheetDocument.Open(StaffEvaluationReport, False)

When it tries to open the copied file for data insertion I got 'File contains corrupted data.'

If I change

Dim extTemplate As String = "C:\Users\User\Desktop\StaffEvalForm\FinalAmendment.xls"

to 

Dim extTemplate As String = "C:\Users\User\Desktop\StaffEvalForm\FinalAmendment.xlsx"

How can I correct this problem?

invalid style

$
0
0

Hi, dear all,

Why the following style sheet can't pass OOXML SDK verification ?

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="x14ac" xmlns:x14ac="http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac">
 <fonts count="4">
  <font>
   <sz val="9"/>
  </font>
  <font>
   <b/>
   <color indexed="0"/>
   <sz val="9"/>
  </font>
  <font>
   <color indexed="0"/>
   <sz val="9"/>
  </font>
  <font>
   <color indexed="1"/>
   <sz val="9"/>
  </font>
 </fonts>
 <borders count="2">
  <border>
   <left>
   </left>
   <right>
   </right>
   <top>
   </top>
   <bottom>
   </bottom>
   <diagonal>
   </diagonal>
   <vertical>
   </vertical>
   <horizontal>
   </horizontal>
  </border>
  <border>
   <left style="thin">
   </left>
   <right style="thin">
   </right>
   <top style="thin">
   </top>
   <bottom style="thin">
   </bottom>
   <diagonal>
   </diagonal>
   <vertical>
   </vertical>
   <horizontal>
   </horizontal>
  </border>
 </borders>
 <cellXfs count="10">
  <xf fontId="1">
  </xf>
  <xf fontId="1" borderId="0">
   <alignment horizontal="right"/>
  </xf>
  <xf fontId="2" borderId="0">
   <alignment horizontal="left"/>
  </xf>
  <xf fontId="1" borderId="1">
   <alignment horizontal="left"/>
  </xf>
  <xf fontId="1" borderId="1">
   <alignment horizontal="right"/>
  </xf>
  <xf fontId="2" borderId="1">
   <alignment horizontal="left"/>
  </xf>
  <xf fontId="2" borderId="1">
   <alignment horizontal="right"/>
  </xf>
  <xf numFmtId="4" fontId="2" borderId="1">
   <alignment horizontal="right"/>
  </xf>
  <xf numFmtId="4" fontId="2" borderId="0">
   <alignment horizontal="left"/>
  </xf>
  <xf numFmtId="4" fontId="3" borderId="0">
   <alignment horizontal="left"/>
  </xf>
 </cellXfs>
</styleSheet>

it reports me unexpected fontsize child errors . What's wrong with this ? many thanks !!!

cannot insert any page numbers Word document Office 2007.

$
0
0
 Insert command does not open to enable me to insert page numbers.
Viewing all 1288 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>