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

How to format Excel cells programmatically using C#?

$
0
0

1. How to format the font to BOLD.  In the cold below, I used f.FontId = 1, but it didn't work.

2. How to add color to the font?

3. How to set the column width with auto max?

4. With f.NumberFormatId = 4, the output is #,##0.00 which is correct. But how can I get 4 decimals, like #,##0.0000?

var excelStyleSheet = new ExcelStylesheet();

                excelStyleSheet.AddCellFormat("Numeric", (f) =>
                {
                    f.NumberFormatId = 4; // #,##0.00
                    f.Alignment = new Alignment() { Horizontal = HorizontalAlignmentValues.Right, Vertical = VerticalAlignmentValues.Center };
                    f.ApplyNumberFormat = BooleanValue.FromBoolean(true);
                });

                excelStyleSheet.AddCellFormat("Header", (f) =>
                {
                    f.FontId = 1;
                    f.Alignment = new Alignment() { Horizontal = HorizontalAlignmentValues.Center, Vertical = VerticalAlignmentValues.Center };
                    f.ApplyFont = BooleanValue.FromBoolean(true);
                });



DOCX Parser

onenxml removing numbering and listbox from word document

$
0
0

Hello

I'm i'm replacing some bookmarks in a word 2010 document with openxml 2.0.

The problem is that it automatically removes all listbox numbering etc. leaving only the text during the elaboration.

This is my code:

WordprocessingDocument wordPackage = WordprocessingDocument.Open(pathDocument, true);


BookmarkReplacer.ReplaceBookmarkText(this.wordPackage, bookMarkName, content);

this.wordPackage.Close();
this.wordPackage.Dispose();


What is the proper way to add strings into a spreadsheet?

$
0
0

Is there a high level call that inserts strings, taking care of all details? It should deal withboth data structures:

(1) GenerateWorksheetPart1Content();

(2) GenerateSharedStringTablePart1Content();

Plus, the repeated strings.

TIA

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

Reflect Code Not Working

$
0
0

"Open XML SDK 2.0 Productivity Tool for Microsoft Office" should be able to generate code for generating documents. The Root Node however for the specific Excel file I want to generate does not give me any code (Fig. 1.1) when I hit reflect code however the sub nodes do show code (Fig. 1.2). I tried reflecting code for some other excel files with no problems.

Is there something I could have done creating the document either adding a password or protecting sheets that would be preventing the reflect code from doing its job? I know I had protected and made hidden a lot of sheets but I tried undoing that protection with the same results.

I also have =Cell values that refer to other foreign excel files in this workbook could that be the issue?

(Fig. 1.1)

(Fig. 1.2)

Can PowerTools for Open XML be used directly, without PowerShell in the middle?

$
0
0

Before I embark in a wild goose chase, perhaps some experienced fellow can provide guidance (and details!)

I have been looking for ways to access the Open SDK reflected code in higher level ways (sometimes writing the functions myself). This would be a good example:

   What is the proper way to add strings into a spreadsheet?

I figure that I should be able to take all the classes included in PowerTools for Open XML and call them directly, right?

PowerTools for Open XML

Has anybody done it? Does it sound doable? Is this the recommended/best practice way?

TIA

What to do with a Help file in XML format?

$
0
0


I recently discovered something that seems to be the answer to my prayers (danke, Cindy for pointing me to OpenXMLDeveloper.org), a higher level access to Open XML:PowerTools for Open XML.

PowerTools for Open XML

Within the download, there is a Help file for the provided set of functions but it is in barely readable XML (OpenXmlPowerTools.dll-Help.xml) format.

Is there any way I can make that content more readable?

TIA



Given a set of coordinates, how do I retrieve the corresponding Cell?

$
0
0

My application needs to change the style of cell "M:15". How do I retrieve that Cell?

TIA

Problem in calculating formulas in word using open xml

$
0
0

Hi Team,

I am generating a word document using open XML. In my word doc i have formulas like

{=IF(<<MERGEFIELD>> > 100,10,0)}
am able to replace the MERGEFIELD with a value lets suppose 50 and when trying to generate the word document the formula is not updating, it just displays as 
{=IF(50 > 100,10,0)}

rather than 0. The value is not updating

please help me out


Harish

Insert a picture into a header or footer of a word processing doc

$
0
0

Hi team,

I have referred to the link http://msdn.microsoft.com/en-us/library/office/bb497430.aspx to add image part in the word doc

public static void InsertAPicture(string document, string fileName)
{
    using (WordprocessingDocument wordprocessingDocument = 
        WordprocessingDocument.Open(document, true))
    {
        MainDocumentPart mainPart = wordprocessingDocument.MainDocumentPart;

        ImagePart imagePart = mainPart.AddImagePart(ImagePartType.Jpeg);

        using (FileStream stream = new FileStream(fileName, FileMode.Open))
        {
            imagePart.FeedData(stream);
        }

        AddImageToBody(wordprocessingDocument, mainPart.GetIdOfPart(imagePart));
    }
}

private static void AddImageToBody(WordprocessingDocument wordDoc, string relationshipId)
{
    // Define the reference of the image.
    var element =
         new Drawing(
             new DW.Inline(
                 new DW.Extent() { Cx = 990000L, Cy = 792000L },
                 new DW.EffectExtent() { LeftEdge = 0L, TopEdge = 0L, 
                     RightEdge = 0L, BottomEdge = 0L },
                 new DW.DocProperties() { Id = (UInt32Value)1U, 
                     Name = "Picture 1" },
                 new DW.NonVisualGraphicFrameDrawingProperties(
                     new A.GraphicFrameLocks() { NoChangeAspect = true }),
                 new A.Graphic(
                     new A.GraphicData(
                         new PIC.Picture(
                             new PIC.NonVisualPictureProperties(
                                 new PIC.NonVisualDrawingProperties() 
                                    { Id = (UInt32Value)0U, 
                                        Name = "New Bitmap Image.jpg" },
                                 new PIC.NonVisualPictureDrawingProperties()),
                             new PIC.BlipFill(
                                 new A.Blip(
                                     new A.BlipExtensionList(
                                         new A.BlipExtension() 
                                            { Uri = "{28A0092B-C50C-407E-A947-70E740481C1C}" })
                                 ) 
                                 { Embed = relationshipId, 
                                     CompressionState = 
                                     A.BlipCompressionValues.Print },
                                 new A.Stretch(
                                     new A.FillRectangle())),
                             new PIC.ShapeProperties(
                                 new A.Transform2D(
                                     new A.Offset() { X = 0L, Y = 0L },
                                     new A.Extents() { Cx = 990000L, Cy = 792000L }),
                                 new A.PresetGeometry(
                                     new A.AdjustValueList()
                                 ) { Preset = A.ShapeTypeValues.Rectangle }))
                     ) { Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture" })
             ) { DistanceFromTop = (UInt32Value)0U, 
                 DistanceFromBottom = (UInt32Value)0U, 
                 DistanceFromLeft = (UInt32Value)0U, 
                 DistanceFromRight = (UInt32Value)0U, EditId = "50D07946" });

   // Append the reference to body, the element should be in a Run.
   wordDoc.MainDocumentPart.Document.Body.AppendChild(new Paragraph(new Run(element)));
}

how can i add image to the header or footer part using the same concept here. Please help me out

 

Harish

Does the Reflected Code fully close the spreadsheet file?

$
0
0

The Open XML SDK-generated source code looks as follows:

// Creates a SpreadsheetDocument.
public void CreatePackage(string filePath)
{
    using(SpreadsheetDocument package = SpreadsheetDocument.Create(filePath, SpreadsheetDocumentType.Workbook))
    {
        CreateParts(package);
    }
}

what is missing is an explicit file close.

The above works fine as long as a spreadsheet is created and that's the end of it. My application, however, has to reopen it (twice), like this:

public void CreatePackage(string filePath)
{
    using(SpreadsheetDocument package = SpreadsheetDocument.Create(filePath, SpreadsheetDocumentType.Workbook))
    {
        CreateParts(package);
    }
    DoExtraModifications();
}

The second pass works erratically, complaining that some parts of the spreadsheet are still open.

TIA.


Inserting Table at Bookmark from passed Array

$
0
0

Attempting to pickup c# enough to automate a few tasks. I have a goal of reading data from a CSV, filtering and manipulating that dataset and then passing the dataset to a Word Table, inserting based on a bookmark. As a start i am trying to pass list to a function ( i may not have the function correctly structured :(  )  based off the code found in an stackoverflow posting . the code was initially in the main part of the cscript file and was attempting to modify it to make it modular so that i can parse and send data to different bookmarks within a given word template. Please advise.

Code currentstate
using System;
using System.Collections.Generic;
using System.Linq;
using LINQtoCSV;
using System.Text;
using System.Threading.Tasks;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;

namespace ConsoleApplication1
{
    class Program
    {

        static void OpenAndAddTextToWordDocument(string FilePath, string BookMarkNameToModify,List<string> TableData)
        {
            // Open a WordprocessingDocument for editing using the file path.
            WordprocessingDocument wordDoc =
                WordprocessingDocument.Open(FilePath, true);
            //marker for main document part
            var mainDocPart = wordDoc.MainDocumentPart;
            //load bookmarks
            var bookmarks = mainDocPart.Document.Body.Descendants<BookmarkStart>();
            //find our bookmark
            var bookmark =
                from bookmarkIndex in bookmarks
                where bookmarkIndex.Name == BookMarkNameToModify
                select bookmarkIndex;
            //get to first element
            OpenXmlElement elem = bookmark.First().Parent;
            //isolate the table to be worked on
            while (!(elem is DocumentFormat.OpenXml.Wordprocessing.Table))
                elem = elem.Parent;
            var foundOurTable = elem;//FOUND THE TABLE
            //save the row you want to copy each time you have data
            var oldRow = elem.Elements<TableRow>().Last();
            DocumentFormat.OpenXml.Wordprocessing.TableRow row = (TableRow)oldRow.Clone();
            //whack old row
            elem.RemoveChild<TableRow>(oldRow);
            //Time to slap our data into the table
            foreach (String[] item in TableData)
            {
                DocumentFormat.OpenXml.Wordprocessing.TableRow newRow = (TableRow)row.Clone();
                var cells = newRow.Elements<DocumentFormat.OpenXml.Wordprocessing.TableCell>();
                //BE SURE YOU HAVE RIGHT DATA COUNT PER ROW BEFORE DOING THIS!!
                for (int i = 0;
                    i < cells.Count();
                    i++)
                {
                    var c = cells.ElementAt(i);
                    var run = c.Elements<Paragraph>().First().Elements<Run>().First();
                    var text = run.Elements<Text>().First();
                    text.Text=item[i];
                }
                foundOurTable.AppendChild(newRow);
            }
            /*Close the handle explicitly.*/
            mainDocPart.Document.Save();
            wordDoc.Close();
        }
        static void Main(string[] args)
        {
            //make some data.
            const string file = @"D:\ScriptData\This is a Test.dotx";
            String[] array1 = { "345", "4356", "345" };
            List<string> listing = new List<string>(array1);
            OpenAndAddTextToWordDocument(file, "JobSummaryTableAttempt1", listing);
            Console.ReadKey();

        }
    }
}

Insert merge field in word using open xml

$
0
0

Hi team,

I want to insert a merge field to an existing word doc. Am able to create a xml element of merge field but am not sure on how to append that to the document. Below is my code 

Microsoft.Office.Interop.Word.Document wrdDoc = Globals.ThisAddIn.Application.ActiveDocument;

From above I will get the active document

string instructionText = String.Format(" MERGEFIELD  {0}  \\* MERGEFORMAT", fieldname);
                SimpleField simpleField1 = new SimpleField() { Instruction = instructionText };
                DocumentFormat.OpenXml.Wordprocessing.Run run1 = new DocumentFormat.OpenXml.Wordprocessing.Run();
                RunProperties runProperties1 = new RunProperties();
                NoProof noProof1 = new NoProof();
                runProperties1.Append(noProof1);
                Text text1 = new Text();
                text1.Text = String.Format("«{0}»", fieldname);
                run1.Append(runProperties1);
                run1.Append(text1);
                simpleField1.Append(run1);
                DocumentFormat.OpenXml.Wordprocessing.Paragraph paragraph = new DocumentFormat.OpenXml.Wordprocessing.Paragraph();
                paragraph.Append(new OpenXmlElement[] { simpleField1 });

Here am creating a paragraph. Now how can i append this paragraph element to the wrdDoc

Harish



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





Open XML avd Word 2007

$
0
0
Hi all!

 I programmatically insert the first document (temlate.xml) into  the second document (dummy.docx) and use the following code taken from official Microsoft site (http://msdn.microsoft.com/en-us/library/office/bb456489.aspx):

    Protected Sub btn_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btn.Click
        Dim fromDocument1 As String ="templates\template.xml"
        Dim toDocument2 As String = "templates\dummy.docx"
     
        AddNewPart(toDocument2, fromDocument1)

    End Sub

    Public Sub AddNewPart(ByVal document As String, ByVal fileName As String)
        Using wordDoc As WordprocessingDocument = WordprocessingDocument.Open(document, True)
            Dim mainPart As MainDocumentPart = wordDoc.MainDocumentPart

            Dim myXmlPart As CustomXmlPart = mainPart.AddCustomXmlPart(CustomXmlPartType.CustomXml)

            Using stream As New FileStream(fileName, FileMode.Open)
                myXmlPart.FeedData(stream)
            End Using
        End Using
    End Sub

But I see nothing in combined document (dummy.docx) althogh when I open this file as archive I see there the part (compressed folder) "customXML". There is the file "item.xml" in this folder, which I can open and  see there the content of my template (Template.xml). That is this content is present in the combined file but I don't see it. What I do wrong?

Is Open XML SDK safe in a windows service?

$
0
0

Is the Open XML SDK safe for use in Windows services (i.e. applications with no user interface). VSTO was known to have code that popped up dialog boxes or do some other UI operations in the case where errors were encountered making it not appropriate for enterprise grade windows services. Does anyone have any good answers about the newer SDK?

Thanks in advance

Open XML SDK, how to delete the pages when I find a certain line in the doc file

$
0
0

Hi,

I am using  Open XML SDK in my C#.NET project and here is what I want to do. First, I need to find a line where is for example written this: "REMOVE THE PAGES BEHIND". When I find that page I need to literally delete pages behind that line. Here is the example:

-----------

Page 1

           ...content....

-----------

Page 2

           ...content....

----------

Page 3

           REMOVE THE PAGES BEHIND

           ...content....

---------

Page 4

---------

So, I need to delete first two pages and leave the rest. I found article which explains how to delete the file, but is there some way to find that line?

Thank you in advance.


Programmatic Merge of SQL Data to a Word Template

$
0
0

I have a client that wants to be able to produce a Customer Profile report based on data that resides in a SQL 2008 R2 db.  They want to choose a customer from a drop-down list in a web page and have it spit out a rather extensive report on that customer.

I was going to use SSRS, but they wanted something that was not only functional but esthetically pleasing, so I'm merging data into a Word document using OpenXML.

Things have been going swimmingly, but I now have a request that I'm not sure how (or even if it is possible) to address with this.

The approach I've used so far is one of place-holders in a Word doc.  You add a control from the Developer Tab, you name it, you wire it up to your XML and you populate it in your CSharp app.  Works like a champ.

Now they want a kind of repeatable section thing.  Let's say that a customer has open projects.  For each of these projects, they would like to see the same set of data elements.  So conceptually, I need a template of place holders that I can populate and then merge into the document.

 

Here's some code:

 

privatevoid CreateDocument( )
		{// Get the template document file and create a stream from itconststring DocumentFile = @"~/App_Data/CustomerProfileTemplate.docx";//			const string DocumentFile = @"~/App_Data/OneOff.docx";// Read the file into memorybyte[ ] buffer = File.ReadAllBytes( Server.MapPath( DocumentFile ) );//			MemoryStream memoryStream = new MemoryStream( buffer, true ); // NoNoNo!!! MemoryStreams created this way cannot expand dynamically!
			MemoryStream memoryStream = new MemoryStream( );

			memoryStream.Capacity = buffer.Length;
			memoryStream.Write( buffer, 0, buffer.Length );
			buffer = null;// Open the document in the stream and replace the custom XML partusing ( Package pkgFile = Package.Open( memoryStream, FileMode.Open, FileAccess.ReadWrite ) )
			{
				PackageRelationshipCollection pkgrcOfficeDocument = pkgFile.GetRelationshipsByType( strRelRoot );foreach ( PackageRelationship pkgr in pkgrcOfficeDocument )
				{if ( pkgr.SourceUri.OriginalString == "/" )
					{// Get the root part
						PackagePart pkgpRoot = pkgFile.GetPart( new Uri( "/" + pkgr.TargetUri.ToString( ), UriKind.Relative ) );// Add a custom XML part to the package
						Uri uriData = new Uri( "/customXML/item1.xml", UriKind.Relative );if ( pkgFile.PartExists( uriData ) )
						{// Delete document "/customXML/item1.xml" part
							pkgFile.DeletePart( uriData );
						}// Load the custom XML data
						PackagePart pkgprtData = pkgFile.CreatePart( uriData, "application/xml" );
						GetDataFromSQLServer( pkgprtData.GetStream( ), ddlCustomer.SelectedValue );
					}
				}// Close the file - not needed thanks to "Using"//			pkgFile.Close( );
			}//Build File Namestring fileName = ddlCustomer.SelectedItem.ToString( ) + " Profile.docx";// Return the result
			Response.ClearContent( );
			Response.ClearHeaders( );
			Response.AddHeader( "content-disposition", "attachment; filename=" + fileName );
			Response.ContentEncoding = System.Text.Encoding.UTF8;

			memoryStream.WriteTo( Response.OutputStream );

			memoryStream.Close( );

			Response.End( );
		}

The function GetDataFromSQLServer( ) is where I get the data and drop it into the doc and looks something like this:

privatevoid GetDataFromSQLServer( Stream stream, string customerID = "" )
		{// Connect to a Microsoft SQL Server database and get data
			String source = System.Configuration.ConfigurationManager.ConnectionStrings[ "BlahBlahBlahConnectionString" ].ConnectionString;using ( SqlConnection conn = new SqlConnection( source ) )
			{
				conn.Open( );
				SqlCommand cmd = new SqlCommand( );
				cmd.CommandText = "dbo.usp_get_data";
				cmd.CommandType = CommandType.StoredProcedure;
				cmd.Connection = conn;

				cmd.Parameters.AddWithValue( "@CompanyId", customerID );
				SqlDataReader dr = cmd.ExecuteReader( );if ( dr.Read( ) )
				{
					XmlWriter writer = XmlWriter.Create( stream );// Get Data string companyName = ( string )dr[ "CompanyName" ];string numEmployees = ( string )dr[ "NumberOfEmployees" ].ToString( );string technologyID = ( string )dr[ "TechnologyID" ];
							. . .
							. . .
							. . .// Title Page
					writer.WriteStartElement( "Customer" );
					writer.WriteElementString( "CompanyName", companyName );
					writer.WriteElementString( "TechnologyID", technologyID );
					writer.WriteElementString( "NumberOfEmployees", numEmployees );
							. . .
							. . .
							. . .


					writer.WriteEndElement( );
					writer.Close( );
				}


				dr.Close( );
				conn.Close( );
			}
		}

Shameful lack of error handling aside, the above process works nicely; the resulting document is beautiful.  The problem is I don't see a way forward from here given the latest requests.

Any thoughts would be very much appreciated.

 

JP

What formula(e) does Office use to apply brightness/contrast adjustments to images?

$
0
0

Microsoft:

I have been trying to figure out how Office 2007 applies brightness/contrast adjustments to images, but I haven't had any luck matching what Office does. I have not found it detailed in any of the Office Open XML documentation, and web searches yield nothing that works exactly like Office. Can you provide the formula(e) that Office uses to apply those adjustments to image color values?

Thanks much,

devfw

Viewing all 1288 articles
Browse latest View live


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