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

How to add carriage return, line feed and bulleted list to Word.docx from code?

$
0
0

i wonder if its because of using plain text content controls instead of rt?

but in the application it opens a word.docx as a template, its got a bunch of content controls.  based on database data and user input it fills in the cc's and sends to the users computer.  wow.

but in one area it needs to be bulleted, and i add carriage returns in the text? but in Word they are ignored.  if my string literal text included string += "\n" then in the textareafor box? its a CRLF (return and linefeed) if i put in+ 0x0a + 0x0d the hex for cr, lf ? it also returns right in the text box not in word.  format chars are ignored when it shows the formulated word doc.

i now tried putting all of the strings into a single content control so it will shape/size right; but they run together.  i copied some text into notepad++ to discover the bullet char, copied that into the code for + "?" whatever the symbol is and it causes a thin lined box instead of a filled in bullet.  no return.

Not sure what to be adding in there to format the data??


Table Width with Percents

$
0
0

Hello.

 

I comming here because i have a problem with colums size in percents in my dynamical tables. In fact i have created a little library wich use OpenXML framework and I fill X tables with datas.

The number of tables is undefined so i create a copy and paste the same pattern at each time and i create a new table in this one.

 

The process works fine, but i have 1 case wich doing weird things.

 

Here a picture of the output in word :


As you can see the column size (especially for the first one) don't have the good size. You can see the real size with this picture wich represent a other table in the same document :


The size of the columns are determined in percent (5000 = 100 %), the % for the first column is 21 % and it's always the same size in other tables except this one. The other columns have 39% & 40 %.

When i put manually the values in Word the columns are resized perfectlly. Here a screenshot of the table modified by word :


So i have tried to check differences in theXML code between thoses 2 tables :

XML of the bad table (3 first columns declaration -  it's the same for the other lines):

<w:tbl><w:tblPr><w:tblStyle w:val="Grilledutableau" /><w:tblW w:w="0" w:type="auto" /><w:tblLook w:val="04A0" /></w:tblPr><w:tblGrid><w:gridCol w:w="10606" /></w:tblGrid><w:tr w:rsidRPr="001301CF" w:rsidR="005301AE" w:rsidTr="00145ABA">//first row is useless here<w:tr w:rsidRPr="001301CF" w:rsidR="005301AE" w:rsidTr="00084BE3"><w:trPr><w:trHeight w:val="11751" /></w:trPr><w:tc><w:tcPr><w:tcW w:type="auto" /></w:tcPr><w:tbl><w:tblPr><w:tblStyle w:val="Grillemoyenne1-Accent1" /><w:tblW w:w="10415" w:type="dxa" /></w:tblPr><w:tblGrid><w:gridCol w:w="2187" /><w:gridCol w:w="4062" /><w:gridCol w:w="4166" /></w:tblGrid><w:tr><w:tc><w:tcPr><w:tcW w:w="1050" w:type="pct" /></w:tcPr><w:p><w:r><w:rPr><w:rFonts w:ascii="Times New Roman" w:hAnsi="Times New Roman" /><w:sz w:val="20" /></w:rPr><w:t>Cable reference</w:t></w:r></w:p></w:tc><w:tc><w:tcPr><w:tcW w:w="1950" w:type="pct" /></w:tcPr><w:p><w:r><w:rPr><w:rFonts w:ascii="Times New Roman" w:hAnsi="Times New Roman" /><w:sz w:val="20" /></w:rPr><w:t>In terminal</w:t></w:r></w:p></w:tc><w:tc><w:tcPr><w:tcW w:w="2000" w:type="pct" /></w:tcPr><w:p><w:r><w:rPr><w:rFonts w:ascii="Times New Roman" w:hAnsi="Times New Roman" /><w:sz w:val="20" /></w:rPr><w:t>Out terminal</w:t></w:r></w:p></w:tc></w:tr>

And here the good table in the other document :

<w:tbl><w:tblPr><w:tblStyle w:val="Grilledutableau" /><w:tblW w:w="0" w:type="auto" /><w:tblLayout w:type="fixed" /><w:tblLook w:val="04A0" /></w:tblPr><w:tblGrid><w:gridCol w:w="10682" /></w:tblGrid><w:tr w:rsidRPr="001301CF" w:rsidR="005301AE" w:rsidTr="00AB6350">//first row useless here<w:tr w:rsidRPr="001301CF" w:rsidR="005301AE" w:rsidTr="00AB6350"><w:trPr><w:trHeight w:val="11751" /></w:trPr><w:tc><w:tcPr><w:tcW w:w="10682" w:type="dxa" /></w:tcPr><w:tbl><w:tblPr><w:tblStyle w:val="Grillemoyenne1-Accent1" /><w:tblW w:w="10446" w:type="dxa" /><w:tblLayout w:type="fixed" /><w:tblLook w:val="04A0" /></w:tblPr><w:tblGrid><w:gridCol w:w="2194" /><w:gridCol w:w="4074" /><w:gridCol w:w="4178" /></w:tblGrid><w:tr w:rsidR="000E3D8F" w:rsidTr="00AB6350"><w:trPr><w:cnfStyle w:val="100000000000" /></w:trPr><w:tc><w:tcPr><w:cnfStyle w:val="001000000000" /><w:tcW w:w="1050" w:type="pct" /></w:tcPr><w:p w:rsidR="000E3D8F" w:rsidRDefault="00B84315"><w:r><w:rPr><w:rFonts w:ascii="Times New Roman" w:hAnsi="Times New Roman" /><w:sz w:val="20" /></w:rPr><w:t>Cable reference</w:t></w:r></w:p></w:tc><w:tc><w:tcPr><w:tcW w:w="1950" w:type="pct" /></w:tcPr><w:p w:rsidR="000E3D8F" w:rsidRDefault="00B84315"><w:pPr><w:cnfStyle w:val="100000000000" /></w:pPr><w:r><w:rPr><w:rFonts w:ascii="Times New Roman" w:hAnsi="Times New Roman" /><w:sz w:val="20" /></w:rPr><w:t>In terminal</w:t></w:r></w:p></w:tc><w:tc><w:tcPr><w:tcW w:w="2000" w:type="pct" /></w:tcPr><w:p w:rsidR="000E3D8F" w:rsidRDefault="00B84315"><w:pPr><w:cnfStyle w:val="100000000000" /></w:pPr><w:r><w:rPr><w:rFonts w:ascii="Times New Roman" w:hAnsi="Times New Roman" /><w:sz w:val="20" /></w:rPr><w:t>Out terminal</w:t></w:r></w:p></w:tc></w:tr>

I have tried a lot of things (like add tablelook + tablelayout) but the rendering is always the same. I have tested to set text in cell then define the width but there is no changes again.

The manually resized Word haven't exact size (21,5%~ for the first column) but the result it's better than the bad one. I have added the GridColumn but nothing change.

The widths are the same, doest the cnfStyle is the solution to the problem ? There is no good explanations about this tag i don't know what it does. And if it's required, why the other tabe aren't affected by the problem and just this one ?

What is my problem, and why Word just resize columns and ignore given size because there is long text in it ? 

 

I have Office 2007 and the version of the OpenXml library is  2.0.5022.0.

 

Thank you in adavance for your help. Sorry if my english is not perfect.

 

Best regards,

Bloopis.



Do Excel row elements in the Sheet1.xml, (Open XML part), have to be in sequence?

$
0
0

This question relates to
 a) "Open XML SDK 2.0 for Microsoft Office",
 b) Excel 2007 and
 c) the downloaded vb snippet "XLInsertNumberIntoCell.snippet"

I am confused regarding the sequence of the row elements in the Sheet1.xml

The code snippet "XLInsertNumberIntoCell" appends a row if it does not exist - without regard to its position.

If I have gaps in my sheet (ie rows that have no corresponding elements in Sheet1.xml) then the snippet adds the new row after the last row element even if the new row's index positions it within the first gap and thus creating an out-of-sequence set of row elements.

The result is that the wordbook is corrupt and Excel offers to repair it on openning it.

On repairing, Excel removes the "out of sequence" row element.

I believe I have confirmed that the row elements need to be sequenced by manually copy/pasting the row elements in Sheet1.xml to change the sequence.
On each occasion when the rows are out-of sequence Excel refuses to open the document.

However, I am under the impression that this snippet is widely used and hence I would be surprised to find such an obvious bug in the code.

So, could somebody please give a difinitive response as to whether or not the row elements need to be in sequence.

If so, then is there a debugged "XLInsertNumberIntoCell" available for download?

If not, then any suggestions where my logic is incorrect?

Siggy

Adjust Shape size to text content (Word)

$
0
0

Cindy

is this the reference you refer to: https://msdn.microsoft.com/en-us/library/office/ff837519.aspx   ?

i have a new problem, should i start a new thread?

in the openxml document in the code, there is a title.  i need a shape block to move/adjust with how much text happens to be there, to adjust based on size;  then there is a table that only needs as many rows as it needs

when the content controls are filled, the word doc then needs to adjust, here is what the resulting doc looks like:

so the first image here, the text is inserted by content controls just fine, but if the text runs too long? the shapes fall apart, how is this fixed??

Unclear code generated by productivity tool

$
0
0

I'm using the Microsoft Productivity tool to help me on a project. It generated some code to create image content. The code works perfectly, but I don't understand why many objects are preceded by an "A." since no A object is ever created. 

The code is below

 private void GenerateDrawingsPart1Content(DrawingsPart drawingsPart1)
        {
            Xdr.WorksheetDrawing worksheetDrawing1 = new Xdr.WorksheetDrawing();
            worksheetDrawing1.AddNamespaceDeclaration("xdr", "http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing");
            worksheetDrawing1.AddNamespaceDeclaration("a", "http://schemas.openxmlformats.org/drawingml/2006/main");

            Xdr.TwoCellAnchor twoCellAnchor1 = new Xdr.TwoCellAnchor() { EditAs = Xdr.EditAsValues.OneCell };

            Xdr.FromMarker fromMarker1 = new Xdr.FromMarker();
            Xdr.ColumnId columnId1 = new Xdr.ColumnId();
            columnId1.Text = "3";
            Xdr.ColumnOffset columnOffset1 = new Xdr.ColumnOffset();
            columnOffset1.Text = "0";
            Xdr.RowId rowId1 = new Xdr.RowId();
            rowId1.Text = "1";
            Xdr.RowOffset rowOffset1 = new Xdr.RowOffset();
            rowOffset1.Text = "0";

            fromMarker1.Append(columnId1);
            fromMarker1.Append(columnOffset1);
            fromMarker1.Append(rowId1);
            fromMarker1.Append(rowOffset1);

            Xdr.ToMarker toMarker1 = new Xdr.ToMarker();
            Xdr.ColumnId columnId2 = new Xdr.ColumnId();
            columnId2.Text = "6";
            Xdr.ColumnOffset columnOffset2 = new Xdr.ColumnOffset();
            columnOffset2.Text = "210317";
            Xdr.RowId rowId2 = new Xdr.RowId();
            rowId2.Text = "5";
            Xdr.RowOffset rowOffset2 = new Xdr.RowOffset();
            rowOffset2.Text = "48769";

            toMarker1.Append(columnId2);
            toMarker1.Append(columnOffset2);
            toMarker1.Append(rowId2);
            toMarker1.Append(rowOffset2);

            Xdr.Picture picture1 = new Xdr.Picture();

            Xdr.NonVisualPictureProperties nonVisualPictureProperties1 = new Xdr.NonVisualPictureProperties();
            Xdr.NonVisualDrawingProperties nonVisualDrawingProperties1 = new Xdr.NonVisualDrawingProperties() { Id = (UInt32Value)2U, Name = "Picture 1" };

            Xdr.NonVisualPictureDrawingProperties nonVisualPictureDrawingProperties1 = new Xdr.NonVisualPictureDrawingProperties();
            A.PictureLocks pictureLocks1 = new A.PictureLocks() { NoChangeAspect = true };

            nonVisualPictureDrawingProperties1.Append(pictureLocks1);

            nonVisualPictureProperties1.Append(nonVisualDrawingProperties1);
            nonVisualPictureProperties1.Append(nonVisualPictureDrawingProperties1);

            Xdr.BlipFill blipFill1 = new Xdr.BlipFill();

            A.Blip blip1 = new A.Blip() { Link = "drawingId" };
            blip1.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");

            A.Stretch stretch1 = new A.Stretch();
            A.FillRectangle fillRectangle1 = new A.FillRectangle();

            stretch1.Append(fillRectangle1);

            blipFill1.Append(blip1);
            blipFill1.Append(stretch1);

            Xdr.ShapeProperties shapeProperties1 = new Xdr.ShapeProperties();

            A.Transform2D transform2D1 = new A.Transform2D();
            A.Offset offset1 = new A.Offset() { X = 2057400L, Y = 171450L };
            A.Extents extents1 = new A.Extents() { Cx = 2267717L, Cy = 734569L };

            transform2D1.Append(offset1);
            transform2D1.Append(extents1);

            A.PresetGeometry presetGeometry1 = new A.PresetGeometry() { Preset = A.ShapeTypeValues.Rectangle };
            A.AdjustValueList adjustValueList1 = new A.AdjustValueList();

            presetGeometry1.Append(adjustValueList1);

            shapeProperties1.Append(transform2D1);
            shapeProperties1.Append(presetGeometry1);

            picture1.Append(nonVisualPictureProperties1);
            picture1.Append(blipFill1);
            picture1.Append(shapeProperties1);
            Xdr.ClientData clientData1 = new Xdr.ClientData();

            twoCellAnchor1.Append(fromMarker1);
            twoCellAnchor1.Append(toMarker1);
            twoCellAnchor1.Append(picture1);
            twoCellAnchor1.Append(clientData1);

            worksheetDrawing1.Append(twoCellAnchor1);

            drawingsPart1.WorksheetDrawing = worksheetDrawing1;
        }
I know that's a lot, but I wanted to provide context and illustrate that there is NOT an "A" object in scope. Thanks!


Reg: docPartCategory (Document Part Category Filter)

$
0
0

Hello,

Can you please help in understand  whats the purpose of docPartCategory (Document Part Category Filter) and docPartin the content control?

thanks

Vimal


regards Vimal

Display image in word document bookmark using Open XML [SDK 2.0] and C# code.

$
0
0

Hi,

I need to implement word document generation using Open XML [SDK 2.0] and C# code.

I have Word document template .docx file with number of Bookmarks. I need to insert an image at a specified Bookmark (or can be between two bookmarks - ImageStart/ImageEnd). Please assist with the relevant C# code. 

In addition, the image is stored in an SQL table [column datatype - Image], hence the code should be able to pull the image from SQL table and display in the Word document at the specified bookmark.

Thanks & Regards,

Gladson Bayer

Archive file cannot be size 0

$
0
0

I'm trying to open a file using the Openxml SDK in Visual Studio. This file is newly created and has no information and has not been opened. I'm opening the file the standard way:

private WordprocessingDocument document = WordprocessingDocument.Open(filePath, true)

However, upon execution of this line, I receive the message:

"Archive file cannot be size 0" and a FileFormatException is thrown. I never received this message when performing the same operations on excel files that were also blank and untouched. Can I prevent this issue, or do they HAVE to have information in them before I can open them from C#? This is something I need to be able to do for my work.

Thanks for any assistance! 


Create Excel Pivot Table With External Datasource

$
0
0

Hi guys.

Was wondering if somebody here has some advice for me, I've been bumping my head against this for a week now. I would like to create an excel spreadsheet with a database connection and a pivot table from code behind, using either C# or VB.Net. Initially I managed to do this with Microsoft.Office.Excel.Interop but numerous websites have told me this isn't a good idea for deployed web applications so I went looking for other alternatives, in this case the Open XML SDK.

With the Open XML SDK I've managed to create an Excel Spreadsheet as well as a connection to the database within it. This works perfectly and I can manually create a PivotTable using the connection without any problem. But creating the Pivot Table programatically is proving to be a bit of a snag. I've manually created a test Excel document and reflected the code using the Open XML SDK 2.0 Productivity Tool, but it seems as if the code that the Productivity Tool generates adds the Pivot Table fields manually, something which I can't do as I don't know which table will be used during program execution. Same goes for the SharedStringTable. As far as I have it the fields should be automatically read from the datasource.

Does anybody have an example nearby that I can use to create the Pivot Table or perhaps have some code/advice that will help? Below is a dropbox link for my test application. I do think I'm either missing something simple or what I'm trying to do is simply impossible, but looking forward to hearing from the experts.

Test app link: https://www.dropbox.com/s/en9j1wyx3i5uoff/OOXML%203.zip?dl=0

Thanks!

Create an Excel Spreadsheet with an image on the First Header with Open Xml

$
0
0

Hello,

I have been trying to make a supposedly simple task of adding an image to the left of the First Header in an Excel Document, but i can't seem to accomplish it.

I have seen a few examples of inserting images but all of them are to insert an image to cells, i also tried to use Code Reflector from the OpenXML SDK Tools, but no clue in making it work. I have been able to insert some text on the header but i have no clue on how to do the same with an image. What i'm looking to acomplish is to have an image on the left side of the First Header and a Title on the right side of the header.

Can someone please shed some light on this with an actual working example?

This is the code i have working to create the excel Document with data from a DataTable

private MemoryStream CreateSummaryExcelDoc(DataTable dataTable)
        {
            MemoryStream s = new MemoryStream();

            //Create excel document
            using (SpreadsheetDocument excelDocument =
                SpreadsheetDocument.Create(s, SpreadsheetDocumentType.Workbook, true))
            {

                var workbookPart = excelDocument.AddWorkbookPart();
                excelDocument.WorkbookPart.Workbook = new Workbook();
                excelDocument.WorkbookPart.Workbook.Sheets = new Sheets();

                var sheetPart = excelDocument.WorkbookPart.AddNewPart<WorksheetPart>();

                var sheetData = new SheetData();
                sheetPart.Worksheet = new Worksheet(sheetData);
                Worksheet ws = sheetPart.Worksheet;

                // Header Text to Insert
                var textToInsert = "&R&B&18My Header Text"; // &R-Right Section f the Header &B- Bold &18-Font Size
                // Insert text to FirstHeader
                InsertHeaderFooter(ws, HeaderType.FirstHeader, textToInsert);

                Sheets sheets = excelDocument.WorkbookPart.Workbook.GetFirstChild<Sheets>();

                string relationshipId = excelDocument.WorkbookPart.GetIdOfPart(sheetPart);
                // Create My Sheet
                Sheet sheet = new Sheet() { Id = relationshipId, SheetId = 1, Name = "My Sheet" };
                sheets.Append(sheet);

                // Table Header Row
                Row headerRow = new Row();
                // Insert the columns
                List<String> columns = new List<string>();
                foreach (DataColumn column in dataTable.Columns)
                {
                    columns.Add(column.ColumnName);

                    Cell cell = new Cell();
                    cell.DataType = CellValues.String;
                    cell.CellValue = new CellValue(column.ColumnName);
                    headerRow.AppendChild(cell);
                }

                sheetData.AppendChild(headerRow);

                // Insert data
                foreach (DataRow dsrow in dataTable.Rows)
                {
                    Row newRow = new Row();
                    foreach (String col in columns)
                    {
                        Cell cell = new Cell();
                        cell.DataType = CellValues.String;
                        cell.CellValue = new CellValue(dsrow[col].ToString());
                        newRow.AppendChild(cell);
                    }

                    sheetData.AppendChild(newRow);
                }
            }

            return s;
        }

And this is function to add text to an Header.

private static void InsertHeaderFooter(Worksheet ws, HeaderType type, String textToInsert)
        {
            HeaderFooter hf = ws.Descendants<HeaderFooter>().FirstOrDefault();
            if (hf == null)
            {
                hf = new HeaderFooter();
                ws.AppendChild<HeaderFooter>(hf);
            }

            // The HeaderFooter node should be there, at this point!
            if (hf != null)
            {
                // You've found the node. Now add the header or footer.
                // Deal with the attributes first:
                switch (type)
                {
                    case HeaderType.EvenHeader:
                    case HeaderType.EvenFooter:
                    case HeaderType.OddHeader:
                    case HeaderType.OddFooter:
                        // Even or odd only? Add a differentOddEven attribute and set
                        // it to "1".
                        hf.DifferentOddEven = true;
                        break;

                    case HeaderType.FirstFooter:
                    case HeaderType.FirstHeader:
                        hf.DifferentFirst = true;
                        break;
                }

                switch (type)
                {
                    // This code creates new header elements, even if they
                    // already exist. Either way, you end up with a
                    // "fresh" element.
                    case HeaderType.AllHeader:
                        hf.EvenHeader = new EvenHeader();
                        hf.EvenHeader.Text = textToInsert;

                        hf.OddHeader = new OddHeader();
                        hf.OddHeader.Text = textToInsert;
                        break;

                    case HeaderType.AllFooter:
                        hf.EvenFooter = new EvenFooter();
                        hf.EvenFooter.Text = textToInsert;

                        hf.OddFooter = new OddFooter();
                        hf.OddFooter.Text = textToInsert;
                        break;

                    case HeaderType.EvenFooter:
                        hf.EvenFooter = new EvenFooter();
                        hf.EvenFooter.Text = textToInsert;
                        break;

                    case HeaderType.EvenHeader:
                        hf.EvenHeader = new EvenHeader();
                        hf.EvenHeader.Text = textToInsert;
                        break;

                    case HeaderType.OddFooter:
                        hf.OddFooter = new OddFooter();
                        hf.OddFooter.Text = textToInsert;
                        break;

                    case HeaderType.OddHeader:
                        hf.OddHeader = new OddHeader();
                        hf.OddHeader.Text = textToInsert;
                        break;

                    case HeaderType.FirstHeader:
                        hf.FirstHeader = new FirstHeader();
                        hf.FirstHeader.Text = textToInsert;
                        break;

                    case HeaderType.FirstFooter:
                        hf.FirstFooter = new FirstFooter();
                        hf.FirstFooter.Text = textToInsert;
                        break;
                }
            }
            ws.Save();
        }

I appreciate any kind of help in this matter. Thanks!

Update Custom Variables using open Xml SDK

$
0
0

I have Code to Update Custom Variables using OpenXml SDK in C# to Update custom variables in document i have added

Hide Copy Code

updateFields.Val=newDocumentFormat.OpenXml.OnOffValue(true);

when i open world document i'm getting following prompt.

"This document contains fields that may refer to other files. Do you want to update the fields in this document?"

 i have used below Macro to update Custom variable on client machine but it's not a convenient option for me as i need to  updated macro on each machine.

WithOptions.UpdateFieldsAtPrint=True.UpdateLinksAtPrint=TrueEndWithForEach l_section InActiveDocument.SectionsForEach l_headerfooter In l_section.Headers l_headerfooter.Range.Fields.UpdateNext l_headerfooterForEach l_headerfooter In l_section.Footers l_headerfooter.Range.Fields.UpdateNext l_headerfooterNext l_sectionActiveDocument.Fields.Update

how i can avoid/hide this prompt .

How to add spreadsheet elements with Style to openxml doc

$
0
0

hi

I am using openXML, using a word .docx file as a template that opens the file, converts to binary[] then modifies then saves and outputs that new document.  That part is ok, but am adding a table acting as spreadsheet elements.

Question is How to modify the Font style so that in the generated table, its applying the already set "Style1" that comes from the word docx file?  in other words, in the template.docx there is a style called Style1.   how to have the table code implement this style1?  right now its always bold 14pt.  Style has the right font and pitch

               revenue   expenses   total

2014    

2015

 

Table table1 = new Table();

            TableProperties tableProperties1 = new TableProperties();
            TableStyle tableStyle1 = new TableStyle(){ Val = "TableGrid" };
            TableWidth tableWidth1 = new TableWidth(){ Width = "0", Type = TableWidthUnitValues.Auto };
            TableLook tableLook1 = new TableLook(){ Val = "04A0", FirstRow = true, LastRow = false, FirstColumn = true, LastColumn = false, NoHorizontalBand = false, NoVerticalBand = true };

            tableProperties1.Append(tableStyle1);
            tableProperties1.Append(tableWidth1);
            tableProperties1.Append(tableLook1);

            TableGrid tableGrid1 = new TableGrid();
            GridColumn gridColumn1 = new GridColumn(){ Width = "2337" };
            GridColumn gridColumn2 = new GridColumn(){ Width = "2337" };
            GridColumn gridColumn3 = new GridColumn(){ Width = "2338" };
            GridColumn gridColumn4 = new GridColumn(){ Width = "2338" };

            tableGrid1.Append(gridColumn1);
            tableGrid1.Append(gridColumn2);
            tableGrid1.Append(gridColumn3);
            tableGrid1.Append(gridColumn4);

            TableRow tableRow1 = new TableRow(){ RsidTableRowAddition = "00EF1E0F", RsidTableRowProperties = "00EF1E0F" };

            TableCell tableCell1 = new TableCell();

            TableCellProperties tableCellProperties1 = new TableCellProperties();
            TableCellWidth tableCellWidth1 = new TableCellWidth(){ Width = "2337", Type = TableWidthUnitValues.Dxa };

            tableCellProperties1.Append(tableCellWidth1);

            Paragraph paragraph1 = new Paragraph(){ RsidParagraphAddition = "00EF1E0F", RsidRunAdditionDefault = "006004F2" };

            Run run1 = new Run();
            Text text1 = new Text();
            text1.Text = "R1c1";

            run1.Append(text1);

            paragraph1.Append(run1);

            tableCell1.Append(tableCellProperties1);
            tableCell1.Append(paragraph1);

            TableCell tableCell2 = new TableCell();

            TableCellProperties tableCellProperties2 = new TableCellProperties();
            TableCellWidth tableCellWidth2 = new TableCellWidth(){ Width = "2337", Type = TableWidthUnitValues.Dxa };

            tableCellProperties2.Append(tableCellWidth2);

            Paragraph paragraph2 = new Paragraph(){ RsidParagraphAddition = "00EF1E0F", RsidRunAdditionDefault = "006004F2" };

            Run run2 = new Run();
            Text text2 = new Text();
            text2.Text = "R1c2";


table coloumn alignment in openxml using C#

$
0
0


If all the values in a column containing decimal values, the decimal align must be applied.

how to do this?


StyleSheet in Excel File Used by Open XML

$
0
0

Hi,

i am using OpenXML for export large amount of data in to excel.

this is working fine but style is not working.

I want to do following in my excel.:-

  • Need to Hide one column in file.
  • Header should be in bold.
  • data type change in 

Please find some piece of code below-

                 using (var workbook = SpreadsheetDocument.Create(file, DocumentFormat.OpenXml.SpreadsheetDocumentType.Workbook))
                {
                    var workbookPart = workbook.AddWorkbookPart();
                    workbook.WorkbookPart.Workbook = new DocumentFormat.OpenXml.Spreadsheet.Workbook();
                    workbook.WorkbookPart.Workbook.Sheets = new DocumentFormat.OpenXml.Spreadsheet.Sheets();

                    uint sheetId = 1;

                    //foreach (DataTable table in ds.Tables)
                    //{
                    var sheetPart = workbook.WorkbookPart.AddNewPart<WorksheetPart>();
                    var sheetData = new DocumentFormat.OpenXml.Spreadsheet.SheetData();
                    sheetPart.Worksheet = new DocumentFormat.OpenXml.Spreadsheet.Worksheet(sheetData);

                    DocumentFormat.OpenXml.Spreadsheet.Sheets sheets = workbook.WorkbookPart.Workbook.GetFirstChild<DocumentFormat.OpenXml.Spreadsheet.Sheets>();
                    string relationshipId = workbook.WorkbookPart.GetIdOfPart(sheetPart);

                    if (sheets.Elements<DocumentFormat.OpenXml.Spreadsheet.Sheet>().Count() > 0)
                    {
                        sheetId =
                            sheets.Elements<DocumentFormat.OpenXml.Spreadsheet.Sheet>().Select(s => s.SheetId.Value).Max() + 1;
                    }

                    DocumentFormat.OpenXml.Spreadsheet.Sheet sheet = new DocumentFormat.OpenXml.Spreadsheet.Sheet() { Id = relationshipId, SheetId = sheetId, Name = AccountPool };
                    sheets.Append(sheet);

                    var cellFormats = workbookPart.WorkbookStylesPart.Stylesheet.CellFormats;
                    DocumentFormat.OpenXml.Spreadsheet.Row headerRow = new DocumentFormat.OpenXml.Spreadsheet.Row();

                    List<String> columns = new List<string>();
                    foreach (DataColumn column in table.Columns)
                    {
                        columns.Add(column.ColumnName);

                        DocumentFormat.OpenXml.Spreadsheet.Cell cell = new DocumentFormat.OpenXml.Spreadsheet.Cell();

                        //date format.  Excel internally represent the datetime value as number, the date is only a formatting
                        //        //applied to the number.  It will look something like 40000.2833 without formatting
                        //        var attributes = new OpenXmlAttribute[] { new OpenXmlAttribute("s", null, "1") }.ToList();

                        var styleIndex = (int)cell.StyleIndex.Value;
                        var cellFormat = (CellFormat)cellFormats.ElementAt(styleIndex);
                        cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.String;
                        //cell.StyleIndex = new OpenXmlAttribute("s", null, "1");
                        cell.CellValue = new DocumentFormat.OpenXml.Spreadsheet.CellValue(column.ColumnName);
                        headerRow.AppendChild(cell);
                    }

                    sheetData.AppendChild(headerRow);

                    foreach (DataRow dsrow in table.Rows)
                    {
                        DocumentFormat.OpenXml.Spreadsheet.Row newRow = new DocumentFormat.OpenXml.Spreadsheet.Row();
                        foreach (String col in columns)
                        {
                            DocumentFormat.OpenXml.Spreadsheet.Cell cell = new DocumentFormat.OpenXml.Spreadsheet.Cell();
                            cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.String;
                            cell.CellValue = new DocumentFormat.OpenXml.Spreadsheet.CellValue(dsrow[col].ToString()); //
                            newRow.AppendChild(cell);
                        }

                        sheetData.AppendChild(newRow);
                    }

Please suggest.

Open XML SDK v2 Handling Multiple Threads

$
0
0

Hi

I have read a post or two that suggests the open XML sdk is not thread safe but I haven't found any official MS document that states this in fact to the contrary most online docs demonstrate how to use the SDK for serverside creation of office documents. I'm prototyping a windows service that reads MSMQ and dispatches a thread to export some data to excel using open xml sdk v2.  The thread is created by calling BeginInvoke on a delegate and ultimately calls this code:

using

(SpreadsheetDocument workBook =SpreadsheetDocument.Open(exportFileInfo.FullName,true))

{

 

WorkbookHelper workBookHelper =newWorkbookHelper(workBook.WorkbookPart, tableName);

exportRowCount =

this.DataBind(workBookHelper, datasource);

workBook.WorkbookPart.Workbook.Save();

workBook.Close();

 

 

return exportRowCount;

}

If I allow 2 or more threads to run concurrently:

  • The code never finishes when I try to export 10000 rows. (I suspect I'm getting deadlock but not sure how to verify this). 
  • It does work if I try to export 5000 rows or less.

If I comment out the calls to save() and close() the code always finishes no matter how many threads I allow to run.  If I allow just one thread to run the exports always works.

Is there a threading problem in the SDK related to saving and closing workbooks and if so is there a plan to fix it soon?

Other than synchronising the entire block of code above is there a way I can I fix the problem myself?

Regards







 


Start application to open docx in a comment location

$
0
0
Is it possible to use the OpenXml API to open a document file in a specific spot, like, for instance, in specific comment location, with the default application to open .docx files (or other application if specified)? I know you can use eitherMicrosoft.Office.Interop.Word to open a word file or the Process.Start, but I need to open the document in a specific location.

OpenXML Excel - How to Remove Formulas

$
0
0

Hi,

I am using OpemXML Excel and I want to remove formulas from each cell and replace with the values only.

Is this possible?

Thanks!

C# - OpenXML SDK 2.5 - Insert New Slide with specific layout

$
0
0

Description

When using Powerpoint directly via the PowerPoint 2007 GUI, I can do the following clicks to have a working PowerPoint file:

  1. Double-Click PowerPoint.exe
  2. Click Save and specify filename (e.g. mytest.pptx)

This file does by default have the Larissa-Theme, which has also by default 9 Layouts associated with it. (Title Slide, Title and Content, Section Header, Comparison etc.)

Lets say I wanted to insert a new Slide with one of these 9 default layouts into mytest.pptx using the OpenXml SDK.

To achieve that I read: https://msdn.microsoft.com/en-au/library/office/cc850834.aspx .

The Code described in that How-To inserts a new slide with the layout from the previous slide. Because I want to insert a new slide with one specific default layout, I googled and found: http://stackoverflow.com/questions/25504305/openxml-set-a-slide-layout-for-a-slide-in-presentation .

Here is my code, which should insert a slide with the layout Comparison into mytest.pptx:

using System;
using DocumentFormat.OpenXml.Presentation;
using DocumentFormat.OpenXml.Packaging;
using Drawing = DocumentFormat.OpenXml.Drawing;
using System.Linq;

namespace TestApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            string somePath = @"C:\mytest.pptx";
            InsertNewSlide(somePath, 1, "");
        }
        public static void InsertNewSlide(string presentationFile, int position, string slideTitle)
        {
            // Open the source document as read/write.
            using (PresentationDocument presentationDocument = PresentationDocument.Open(presentationFile, true))
            {
                // Pass the source document and the position and title of the slide to be inserted to the next method.
                InsertNewSlide(presentationDocument, position, slideTitle);
            }
        }

        // Insert the specified slide into the presentation at the specified position.
        public static void InsertNewSlide(PresentationDocument presentationDocument, int position, string slideTitle)
        {

            if (presentationDocument == null)
            {
                throw new ArgumentNullException("presentationDocument");
            }

            if (slideTitle == null)
            {
                throw new ArgumentNullException("slideTitle");
            }

            PresentationPart presentationPart = presentationDocument.PresentationPart;

            // Verify that the presentation is not empty.
            if (presentationPart == null)
            {
                throw new InvalidOperationException("The presentation document is empty.");
            }

            // Declare and instantiate a new slide.
            Slide slide = new Slide(new CommonSlideData(new ShapeTree()));
            uint drawingObjectId = 1;

            // Construct the slide content.
            // Specify the non-visual properties of the new slide.
            NonVisualGroupShapeProperties nonVisualProperties = slide.CommonSlideData.ShapeTree.AppendChild(new NonVisualGroupShapeProperties());
            nonVisualProperties.NonVisualDrawingProperties = new NonVisualDrawingProperties() { Id = 1, Name = "" };
            nonVisualProperties.NonVisualGroupShapeDrawingProperties = new NonVisualGroupShapeDrawingProperties();
            nonVisualProperties.ApplicationNonVisualDrawingProperties = new ApplicationNonVisualDrawingProperties();

            // Specify the group shape properties of the new slide.
            slide.CommonSlideData.ShapeTree.AppendChild(new GroupShapeProperties());

            // Declare and instantiate the title shape of the new slide.
            Shape titleShape = slide.CommonSlideData.ShapeTree.AppendChild(new Shape());

            drawingObjectId++;

            // Specify the required shape properties for the title shape.
            titleShape.NonVisualShapeProperties = new NonVisualShapeProperties
                (new NonVisualDrawingProperties() { Id = drawingObjectId, Name = "Title" },
                new NonVisualShapeDrawingProperties(new Drawing.ShapeLocks() { NoGrouping = true }),
                new ApplicationNonVisualDrawingProperties(new PlaceholderShape() { Type = PlaceholderValues.Title }));
            titleShape.ShapeProperties = new ShapeProperties();

            // Specify the text of the title shape.
            titleShape.TextBody = new TextBody(new Drawing.BodyProperties(),
                    new Drawing.ListStyle(),
                    new Drawing.Paragraph(new Drawing.Run(new Drawing.Text() { /*Text = slideTitle*/ })));

            // Declare and instantiate the body shape of the new slide.
            Shape bodyShape = slide.CommonSlideData.ShapeTree.AppendChild(new Shape());
            drawingObjectId++;

            // Specify the required shape properties for the body shape.
            bodyShape.NonVisualShapeProperties = new NonVisualShapeProperties(new NonVisualDrawingProperties() { Id = drawingObjectId, Name = "Content Placeholder" },
                    new NonVisualShapeDrawingProperties(new Drawing.ShapeLocks() { NoGrouping = true }),
                    new ApplicationNonVisualDrawingProperties(new PlaceholderShape() { Index = 1 }));
            bodyShape.ShapeProperties = new ShapeProperties();

            // Specify the text of the body shape.
            bodyShape.TextBody = new TextBody(new Drawing.BodyProperties(),
                    new Drawing.ListStyle(),
                    new Drawing.Paragraph());

            // Create the slide part for the new slide.
            SlidePart slidePart = presentationPart.AddNewPart<SlidePart>();

            // Save the new slide part.
            slide.Save(slidePart);

            // Modify the slide ID list in the presentation part.
            // The slide ID list should not be null.
            SlideIdList slideIdList = presentationPart.Presentation.SlideIdList;

            // Find the highest slide ID in the current list.
            uint maxSlideId = 1;
            SlideId prevSlideId = null;

            foreach (SlideId slideId in slideIdList.ChildElements)
            {
                if (slideId.Id > maxSlideId)
                {
                    maxSlideId = slideId.Id;
                }

                position--;
                if (position == 0)
                {
                    prevSlideId = slideId;
                }

            }

            maxSlideId++;

            // Get the ID of the previous slide.
            SlidePart lastSlidePart;

            if (prevSlideId != null)
            {
                lastSlidePart = (SlidePart)presentationPart.GetPartById(prevSlideId.RelationshipId);
            }
            else
            {
                lastSlidePart = (SlidePart)presentationPart.GetPartById(((SlideId)(slideIdList.ChildElements[0])).RelationshipId);
            }




            // Get SlideMasterPart and SlideLayoutPart from the existing Presentation Part
            string layoutName = "Comparison";
            SlideMasterPart slideMasterPart = presentationPart.SlideMasterParts.First();
            SlideLayoutPart slideLayoutPart = slideMasterPart.SlideLayoutParts.SingleOrDefault
                (sl => sl.SlideLayout.CommonSlideData.Name.Value.Equals(layoutName, StringComparison.OrdinalIgnoreCase));
            if (slideLayoutPart == null)
            {
                throw new Exception("The slide layout " + layoutName + " is not found");
            }

            slidePart.AddPart<SlideLayoutPart>(slideLayoutPart);

            // Insert the new slide into the slide list after the previous slide.
            SlideId newSlideId = slideIdList.InsertAfter(new SlideId(), prevSlideId);
            newSlideId.Id = maxSlideId;
            newSlideId.RelationshipId = presentationPart.GetIdOfPart(slidePart);

            // Save the modified presentation.
            presentationPart.Presentation.Save();
        }

    }
}

Problem

The Comparison layout contains 5 Shapes, but only 2 of these Shapes are inserted by my method described above.

Question

How can I insert all 5 Shapes contained in the Comparison Layout into the new Slide?


C# - OpenXML SDK 2.5 - Insert New Slide from Slide Masters with the layout that contains images

$
0
0

I used this https://codingthedocument.wordpress.com/author/agschwantes/ to create my new slides with the help of the OpenXML 2.5 SDK. I designed and used my own Slide Master to create a new slide. My Slide Master includes some layouts with images and some layouts without images.

If I create a slide from my Master Layout without images, everything works fine. If I create a slide with the layout, that contains images, I get the right layout BUT on top of every fixed images there is another movable image overlapping the fixed one, so there are unnecessary duplicates of fixed images, that I don't need in my new created slide.

How can I solve this problem?

My code is below:

public static void InsertNewSlide(string presentationFile, int position, string layoutName)
      {
        using (PresentationDocument presentationDocument = PresentationDocument.Open(presentationFile, true))
        {

            InsertNewSlide(presentationDocument, position, layoutName);
        }
      }

    public static void InsertNewSlide(PresentationDocument presentationDocument, int position, string layoutName)
    {
        PresentationPart presentationPart = presentationDocument.PresentationPart;

        OpenXML.Slide slide = new OpenXML.Slide(new CommonSlideData(new ShapeTree()));

        SlidePart slidePart = presentationPart.AddNewPart<SlidePart>();

        slide.Save(slidePart);

        SlideMasterPart slideMasterPart = presentationPart.SlideMasterParts.First();

        SlideLayoutPart slideLayoutPart = slideMasterPart.SlideLayoutParts.SingleOrDefault(sl => sl.SlideLayout.CommonSlideData.Name.Value.Equals(layoutName, StringComparison.OrdinalIgnoreCase));

        slidePart.AddPart<SlideLayoutPart>(slideLayoutPart);

        slidePart.Slide.CommonSlideData = (CommonSlideData)slideMasterPart.SlideLayoutParts.SingleOrDefault(sl => sl.SlideLayout.CommonSlideData.Name.Value.Equals(layoutName)).SlideLayout.CommonSlideData.Clone();

        using (Stream stream = slideLayoutPart.GetStream())
        {
            slidePart.SlideLayoutPart.FeedData(stream);

        }

        foreach (ImagePart iPart in slideLayoutPart.ImageParts)
        {
             ImagePart newImagePart = slidePart.AddImagePart(iPart.ContentType, slideLayoutPart.GetIdOfPart(iPart));
                                                        newImagePart.FeedData(iPart.GetStream());
        }

        uint maxSlideId = 1;
        SlideId prevSlideId = null;
        var slideIdList = presentationPart.Presentation.SlideIdList;
        foreach (SlideId slideId in slideIdList.ChildElements)
        {
            if (slideId.Id > maxSlideId)
            {
                maxSlideId = slideId.Id;
            }

            position--;
            if (position == 0)
            {
                prevSlideId = slideId;
            }

        }
        maxSlideId++;
        SlideId newSlideId = slideIdList.InsertAfter(new SlideId(), prevSlideId);
        newSlideId.Id = maxSlideId;
        newSlideId.RelationshipId = presentationPart.GetIdOfPart(slidePart);

        presentationPart.Presentation.Save();
    }

}

xlsx not opening in *some* mobile apps

$
0
0

Hello,  

I have an app that generates an xlsx download through the OpenXML 2.5 SDK.  It opens in Excel on the desktop without issue. Validation (both in code and by using the Open XML 2.5 Productivity Tool) reports no errors.

My users have reported that iPhone and iPad fail to open it using either Excel or Google Sheets.  My Android device opens it using Google Sheets or Excel without issue, but Polaris Office 6.5.2 shows only the last row of data.

If I open the file on the desktop in Excel and re-save it, my Android now can open it with Polaris Office as well.  iPad is opening it properly in whatever its default app is.

Comparing the original file with the re-saved one shows that they're vastly different (different namespaces are in use, the cell contents have all been moved to the shared strings table, etc.)

It would seem that *something* is wrong with the file that isn't detected with the SDK validation.  Does anyone know of a way to debug these issues?  A more rigorous validator?  Any insight would be most appreciated.

thanks

Viewing all 1288 articles
Browse latest View live


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