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

Creating Powerpoint with charts using open xml

$
0
0

I wish to create a powerpoint file and then add charts to that file dymanically (chart on each page) through providing the chart title and the chart data and selecting one of the predefined charts titles.

I thought the easiest way to start was to create a presentation with 1 chart (1 slide) and generate code for that using the Open XML SDK tools.

But the code generated is too complicated to be easily read.

 

Please let me know what is the best way to do this?

Thanks in advance 


find sections in docx and copy to docx.

$
0
0

May I copy some sections from docx file? Should I open docx file(there are no problems), find sections with hyperlink there, create a new docx file and copy these sections from hyperlink to docx file (C#) 

Problem to get value

$
0
0
Hi,
I do not get the value of cell.StyleIndex.Value, within the following codes
                                WorksheetPart worksheetPart = (WorksheetPart)workbookPart.GetPartById(sheet.Id);
                                WorkbookStylesPart wstylePart = workbookPart.WorkbookStylesPart;
                                Stylesheet ss = wstylePart.Stylesheet;

                                foreach (Cell cell in worksheetPart.Worksheet.Descendants<Cell>())
                                {
                                    if (cell.StyleIndex != null)
                                    {
                                    ...


against this file. Why?


Many Thanks & Best Regards, Hua Min

How do I change the size of the table, then the chart in a .docx from code?

$
0
0

hi

Am using OpenXML and the DocumentBuilder to open report documents and get the 1st and last items and put them into a new blank Word.docx

The problem is how to resize them?  Here is the xml showing the Table,

<w:document xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:c="http://schemas.openxmlformats.org/drawingml/2006/chart" xmlns:wpc="http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:wp14="http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing" xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" xmlns:w10="urn:schemas-microsoft-com:office:word" xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml" xmlns:wpg="http://schemas.microsoft.com/office/word/2010/wordprocessingGroup" xmlns:wpi="http://schemas.microsoft.com/office/word/2010/wordprocessingInk" xmlns:wne="http://schemas.microsoft.com/office/word/2006/wordml" xmlns:wps="http://schemas.microsoft.com/office/word/2010/wordprocessingShape" mc:Ignorable="w14 wp14"><w:body><w:p w:rsidR="00B53D27" w:rsidRDefault="009E519C"><w:r><w:t xml:space="preserve">This paragraph shall constitute the first </w:t></w:r><w:proofErr w:type="spellStart" /><w:r><w:t>breadswidth</w:t></w:r><w:proofErr w:type="spellEnd" /><w:r><w:t>.</w:t></w:r></w:p><w:tbl><w:tblPr><w:tblStyle w:val="TableGrid" /><w:tblW w:w="10800" w:type="dxa" />

The table width is also found in the reflected code:

 Table table1 = new Table();

            TableProperties tableProperties1 = new TableProperties();
            TableStyle tableStyle1 = new TableStyle(){ Val = "TableGrid" };
            TableWidth tableWidth1 = new TableWidth(){ Width = "10800", Type = TableWidthUnitValues.Dxa };

I want to modify the size of the table here, and then resize the chart so they are the same width and will fit 2-wide on the page.

Here is the general code used to parse one of the report.docx files, there will be 100 or so.  The goal is to squish the table/chart from each report.docx so they will fit 2 wide on a new page;  

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Validation;
using OpenXmlPowerTools;

namespace DocumentBuilderExample
{
    class DocumentBuilderExample
    {
        static void Main(string[] args)
        {
            var n = DateTime.Now;
            var tempDi = new DirectoryInfo(string.Format("ExampleOutput-{0:00}-{1:00}-{2:00}-{3:00}{4:00}{5:00}", n.Year - 2000, n.Month, n.Day, n.Hour, n.Minute, n.Second));
            tempDi.Create();
            string source1 = "../../Source1.docx";
            string source2 = "../../Source1.docx";
            string source3 = "../../templage.docx";
            List<Source> sources = null;
            // Create new document from 10 paragraphs starting at paragraph 5 of Source1.docx
            sources = new List<Source>()
            {
                 new Source(new WmlDocument(source3), 0, 1, true),
                 new Source(new WmlDocument(source1), 0, 2, false),
                 new Source(new WmlDocument(source2), 19, 1, false)
            };
            DocumentBuilder.BuildDocument(sources, Path.Combine(tempDi.FullName, "Out1.docx"));
         }
    }
}

The above code will take my report doc and get the 1st and last item and put that into a new docx file.  but the size is untouched from the original.  

Using the XElement or by any method known, how could the object(s) be accessed so the size could be modified?

Convert the visio file to PDF format Using C#

$
0
0

Hi 

I am working on  convert visio file (which is stored in Sharepoint) to PDF format by having print button.I have used the Microsoft.Office.Interop.Visio.Application  library to convert which is not working . so please tell me is there any alternative way to convert my visio file to Pdf .

I am Using these technologies (Mvc ,web api  and  Jquerry )

Thanks

Problem to Embedded statement

$
0
0
Hi,
Any advice to this
Error2Embedded statement cannot be a declaration or labeled statement

due to 2nd line below. Why?
                        string vIT = "";
                        int index = InsertSharedStringItem(vIT, shareStringPart);

        private static int InsertSharedStringItem(string text, SharedStringTablePart shareStringPart)
        {
            if (shareStringPart.SharedStringTable == null)
            {
                shareStringPart.SharedStringTable = new SharedStringTable();
            }

            int i = 0;
            foreach (SharedStringItem item in shareStringPart.SharedStringTable.Elements<SharedStringItem>())
            {
                if (item.InnerText == text)
                {
                    return i;
                }

                i++;
            }
            shareStringPart.SharedStringTable.AppendChild(new SharedStringItem(new DocumentFormat.OpenXml.Spreadsheet.Text(text)));
            shareStringPart.SharedStringTable.Save();
            return i;
        }



Many Thanks & Best Regards, Hua Min

Powerpoint deletes relation of CustomXmlPart to Slide

$
0
0

Hello.

With the OpenXml SDK 2.5 I added a CustomXmPart to a SlidePart. I added an CustomXmlPropertiesPart and finally added an additional relationship from CustomXmlPart to the PresentationPart. On the first view the Powerpoint.pptx-File looks OK, but after opening and saving the file with Powerpoint the relation from the CustomXmlPart to the SlidePart has gone from the file and is not found programmatically either.

I compared the file to files we created with the Office.Core Library and seemed to have the same structure now.

Did I forgot a relationship or anything else?

Thanks for help.

Locate the error

$
0
0
Hi,
To this Stacktrace
Exception: The specified package is invalid. The main part is missing.    at DocumentFormat.OpenXml.Packaging.OpenXmlPackage.Load()
   at DocumentFormat.OpenXml.Packaging.OpenXmlPackage.OpenCore(String path, Boolean readWriteMode)
   at DocumentFormat.OpenXml.Packaging.SpreadsheetDocument.Open(String path, Boolean isEditable, OpenSettings openSettings)
   at DocumentFormat.OpenXml.Packaging.SpreadsheetDocument.Open(String path, Boolean isEditable)
   at App12.Program.ReadFile(String par_File)


which line should be with the error? How to further find out reason to such error? But now the Stacktrace is NOT pointing out which line is having PROBLEM!

Many Thanks & Best Regards, Hua Min



Open XML run-time instead of SDK

$
0
0

This question is related to understand a better way of releasing my application.

I have an application that process Excel Spreadsheets with Open XML SDK.I'm thinking of mentioning it as a prerequisite of my application so that users can download it beforehand.

My question is, whether there is a Open XML run-time only installer that a non technical user cold use. Because the "Open XML SDK" is convincing that it is a developer tool.

Appreciate your thoughts and suggestion in advance on this.

Excel file not created as expected

$
0
0
Hi,
Excel file is not created by these codes
                        string Path0="c:\\dp2\\Ex0.xlsx";
                        CreateSpreadsheetWorkbook3(Path0);

        public static void CreateSpreadsheetWorkbook3(string filepath)
        {
            // Create a spreadsheet document by supplying the filepath.
            // By default, AutoSave = true, Editable = true, and Type = xlsx.
            SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.
                Create(filepath, SpreadsheetDocumentType.Workbook);

            // Add a WorkbookPart to the document.
            WorkbookPart workbookpart = spreadsheetDocument.AddWorkbookPart();
            workbookpart.Workbook = new DocumentFormat.OpenXml.Spreadsheet.Workbook();

            // Add a WorksheetPart to the WorkbookPart.
            WorksheetPart worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
            worksheetPart.Worksheet = new DocumentFormat.OpenXml.Spreadsheet.Worksheet(new SheetData());

            // Add Sheets to the Workbook.
            DocumentFormat.OpenXml.Spreadsheet.Sheets sheets = spreadsheetDocument.WorkbookPart.Workbook.
                AppendChild<DocumentFormat.OpenXml.Spreadsheet.Sheets>(new DocumentFormat.OpenXml.Spreadsheet.Sheets());

            // Append a new worksheet and associate it with the workbook.
            Sheet sheet = new Sheet()
            {
                Id = spreadsheetDocument.WorkbookPart.
                    GetIdOfPart(worksheetPart),
                SheetId = 1,
                Name = "mySheet"
            };
            sheets.Append(sheet);

            workbookpart.Workbook.Save();

            // Close the document.
            spreadsheetDocument.Close();
        }



Why?

Many Thanks & Best Regards, Hua Min

TextWrappingValues

$
0
0

Hello,

How do I set the TextWrappingValue to Around in my C# open xml file.

TableStyle tableStyle = new TableStyle() { Val = "TableGrid" };
                TableLook tableLook = new TableLook() { Val = "04A0" };
                TextWrappingValues tableTextWrapping = TextWrappingValues.Around;
                tableProperties.Append(tableTextWrapping);

I get the following error on the append:
cannot convert from ‘DocumentFormat.OpenXml.Wordprocessing.TextWrappingValues’ to ‘System.Collections.Generic.IEnumerable<DocumentFormat.OpenXml.OpenXmlElement>’

Thanks,

KS


keith

How to modify the font size of a document from code

$
0
0

How can the parts of the document be discovered and the fontsize changed?

Here is a sample table used,


<w:sdt docpart="2CFD5BC34C8546929C222BE9FE7FE85A" id="-566108754" sdttag="content control 1" showingplchdr="t" title="content control 1">Main Title here.</w:sdt>   <w:sdt docpart="B3E0DD81C49046B5BB844C80F7E0D939" id="1165130247">Date of Report</w:sdt> 

Salesman name:  <w:sdt docpart="B3E0DD81C49046B5BB844C80F7E0D939" id="193582825" showingplchdr="t">John Smith</w:sdt>       Another textbox:  <w:sdt docpart="B3E0DD81C49046B5BB844C80F7E0D939" id="-1475904701" showingplchdr="t">Jane Smith.</w:sdt>

RunProperties runprop = new RunProperties(); Run run = new Run(); Run run2 = new Run(); FontSize fonz = new FontSize(); RunProperties runprop2 = new RunProperties(); RunFonts runf = new RunFonts(); foreach (DocumentFormat.OpenXml.Wordprocessing.TableRow tableRow in table.Descendants<DocumentFormat.OpenXml.Wordprocessing.TableRow>()) { i++; foreach (DocumentFormat.OpenXml.Wordprocessing.TableCell tableCell in tableRow.Descendants<DocumentFormat.OpenXml.Wordprocessing.TableCell>()) { j++; DocumentFormat.OpenXml.Wordprocessing.Paragraph para = tableCell.GetFirstChild<DocumentFormat.OpenXml.Wordprocessing.Paragraph>(); run = para.GetFirstChild<Run>(); if (run != null) {

// run or para, both have the same result fonz = run.Descendants<DocumentFormat.OpenXml.Wordprocessing.FontSize>().FirstOrDefault(); fonz.Val = "6"; } } }

Here if this code runs, the text outside of the content controls is changed to '6' fontsize.  but the top part is only content control and the bottom is label + content control.   The label here is "Salesman name:" and "Another textbox"

Using the above reference the fontsize of this can be changed, but the text inside the sdt's is not touched

How are these parts 'addressed' to be able to change the properties?


Create if not existed

$
0
0
Hi,
I want to create Worksheet with name vSN, if it IS NOT existing on Workbook. How?
                            IEnumerable<Sheet> sheets = spreadSheet.WorkbookPart.Workbook.Descendants<Sheet>().Where(s => s.Name == vSN);
                            if (sheets.Count() == 0)
                            {
                                ...
                            }



Many Thanks & Best Regards, Hua Min

Problem to Append line

$
0
0
Hi,
How to resolve
Error	2	'System.Collections.Generic.IEnumerable<DocumentFormat.OpenXml.Spreadsheet.Sheet>' does not contain a definition for 'Append' and no extension method 'Append' accepting a first argument of type 'System.Collections.Generic.IEnumerable<DocumentFormat.OpenXml.Spreadsheet.Sheet>' could be found (are you missing a using directive or an assembly reference?)	C:\App0\App5\Program.cs	166	40	App5


due to Append line below?
                            IEnumerable<Sheet> sheets = spreadSheet.WorkbookPart.Workbook.Descendants<Sheet>().Where(s => s.Name == vSN);
                            if (sheets.Count() == 0)
                            {
                                // Add a WorkbookPart to the document.
                                WorkbookPart workbookpart = spreadSheet.AddWorkbookPart();
                                workbookpart.Workbook = new DocumentFormat.OpenXml.Spreadsheet.Workbook();

                                // Add a WorksheetPart to the WorkbookPart.
                                WorksheetPart worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
                                worksheetPart.Worksheet = new DocumentFormat.OpenXml.Spreadsheet.Worksheet(new SheetData());

                                Sheet sheet = new Sheet()
                                {
                                    Id = spreadSheet.WorkbookPart.
                                        GetIdOfPart(worksheetPart),
                                    SheetId = 1,
                                    Name = vSN
                                };
                                sheets.Append(sheet);

                            }
                            



Many Thanks & Best Regards, Hua Min

Problem to line

$
0
0
Hi,
How to resolve
Error	2	'DocumentFormat.OpenXml.OpenXmlElement' does not contain a definition for 'Id' and no extension method 'Id' accepting a first argument of type 'DocumentFormat.OpenXml.OpenXmlElement' could be found (are you missing a using directive or an assembly reference?)	C:\App0\App5\Program.cs	170	127	App5


due to last line below?
                        using (SpreadsheetDocument spreadSheet = SpreadsheetDocument.Open(@Path0, true))
                        {
                            ...
                            WorksheetPart worksheetPart2 = (WorksheetPart)spreadSheet.WorkbookPart.GetPartById(sheets.First().Id);



Many Thanks & Best Regards, Hua Min



Problem to write to Worksheet with InnerText

$
0
0
Hi,
I cannot properly write to Worksheet with values by codes below, while there're values to vCO, vRO, vSI, and vIT (vIT is having value to InnerText). Why?
                        using (SpreadsheetDocument spreadSheet = SpreadsheetDocument.Open(@Path0, true))
                        {
                            if (vIT != "")
                            {
                                index = InsertSharedStringItem(vIT, shareStringPart);
                            }
                            IEnumerable<Sheet> sheets = spreadSheet.WorkbookPart.Workbook.Descendants<Sheet>().Where(s => s.Name == vSN);
                            // if the specific sheet doesnot exist, create new
                            if (sheets.Count() == 0)
                            {
                                InsertWorksheetCus(spreadSheet.WorkbookPart, vSN);
                            }
                            // get the worksheetPart
                            WorksheetPart worksheetPart2 = (WorksheetPart)spreadSheet.WorkbookPart.GetPartById(sheets.First().Id);

                            string columnName;
                            uint rowIndex;
                            if (vCO != "" && vRO != "")
                            {
                                columnName = vCO + vRO;
                                rowIndex = Convert.ToUInt32(vRO);
                                Cell cell = InsertCellInWorksheet(columnName, rowIndex, worksheetPart2);
                                if (vSI != "")
                                    cell.StyleIndex = Convert.ToUInt32(vSI);

                                if (index != 0)
                                {
                                    cell.CellValue = new CellValue(index.ToString());
                                    cell.DataType = new EnumValue<CellValues>(CellValues.SharedString);
                                }

                                worksheetPart2.Worksheet.Save();
                            }
                            ...

        private static Cell InsertCellInWorksheet(string columnName, uint rowIndex, WorksheetPart worksheetPart)
        {
            DocumentFormat.OpenXml.Spreadsheet.Worksheet worksheet = worksheetPart.Worksheet;
            SheetData sheetData = worksheet.GetFirstChild<SheetData>();
            string cellReference = columnName + rowIndex;
            Row row;
            if (sheetData.Elements<Row>().Where(r => r.RowIndex == rowIndex).Count() != 0)
            {
                row = sheetData.Elements<Row>().Where(r => r.RowIndex == rowIndex).First();
            }
            else
            {
                row = new Row() { RowIndex = rowIndex };
                sheetData.Append(row);
            }
            if (row.Elements<Cell>().Where(c => c.CellReference.Value == columnName + rowIndex).Count() > 0)
            {
                return row.Elements<Cell>().Where(c => c.CellReference.Value == cellReference).First();
            }
            else
            {
                Cell refCell = null;
                foreach (Cell cell in row.Elements<Cell>())
                {
                    if (string.Compare(cell.CellReference.Value, cellReference, true) > 0)
                    {
                        refCell = cell;
                        break;
                    }
                }
                Cell newCell = new Cell() { CellReference = cellReference };
                row.InsertBefore(newCell, refCell);
                worksheet.Save();
                return newCell;
            }
        }



Many Thanks & Best Regards, Hua Min

Handling Dangling CustomXMLPart when replacing CustomXML from a Word Template

$
0
0

I am creating a Word Template with a Custom XML part linked to content controls in my template. I then replace the Custom XML Part in my code using this code:

        protected void ReplaceCustomXML(string fileName, string customXML)
        {
            using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(fileName, true))
            {
                MainDocumentPart mainPart = wordDoc.MainDocumentPart;
                mainPart.DeleteParts<CustomXmlPart>(mainPart.CustomXmlParts);
                //Add a new customXML part and then add the content.
                CustomXmlPart customXmlPart = mainPart.AddCustomXmlPart(CustomXmlPartType.CustomXml);//(<CustomXmlPart>();// AddNewPart<CustomXmlPart>();
                //Copy the XML into the new part.
                using (StreamWriter ts = new StreamWriter(customXmlPart.GetStream())) ts.Write(customXML);
            }
        }

My original custom XML is this:

<Person><Name>John Smith</Name><Age>15</Age><Phone>555-5555</Phone></Person>

My new custom XML is this:

<Person><Name>Jane Doe</Name><Age>25</Age></Person>

Is there a way to not show the Phone number if it doesn't exist in the new XML? Right now it shows the Phone number that is set in the Word Template since it can't find a new phone number.

table of content in word xml

$
0
0

i wanted to create a word document dynamically. i am able to create the contents of the file and table of content. i gave a hyperlink to the pages from each topic in the table of content. but i am not able to give the page number for the page in table of content

please help me with this issue

Convert Word to HTML with Track Changes

$
0
0

Hello,

I want to convert my word document into HTM Tags with track changes highlighted. I am able to convert word document to html but text present in word document having track changes are resulting as simple plain text in HTML I want to show them in background colour as yellow in HTML please help

            byte[] byteArray = File.ReadAllBytes(@"C:\Users\admin\Desktop\New Microsoft Word Document.docx");

            using (MemoryStream memoryStream = new MemoryStream())
            {
                memoryStream.Write(byteArray, 0, byteArray.Length);
                using (WordprocessingDocument doc = WordprocessingDocument.Open(memoryStream, true))
                {
                    int imageCounter = 0;
                    HtmlConverterSettings settings = new HtmlConverterSettings()
                    {
                        PageTitle = "My Page Title",
                        ImageHandler = imageInfo =>
                        {
                            DirectoryInfo localDirInfo = new DirectoryInfo(@"C:\Users\admin\Desktop\img");
                            if (!localDirInfo.Exists)
                            {
                                localDirInfo.Create();
                            }++imageCounter;
                            string extension = imageInfo.ContentType.Split('/')[1].ToLower();
                            ImageFormat imageFormat = null;
                            if (extension == "png")
                            {
                                extension = "gif";
                                imageFormat = ImageFormat.Gif;
                            }
                            else if (extension == "gif")
                                imageFormat = ImageFormat.Gif;
                            else if (extension == "bmp")
                                imageFormat = ImageFormat.Bmp;
                            else if (extension == "jpeg")
                                imageFormat = ImageFormat.Jpeg;
                            else if (extension == "tiff")
                            {
                                extension = "gif";
                                imageFormat = ImageFormat.Gif;
                            }
                            else if (extension == "x-wmf")
                            {
                                extension = "wmf";
                                imageFormat = ImageFormat.Wmf;
                            }
                            if (imageFormat == null)
                                return null;

                            string imageFileName = @"C:/Users/admin/Desktop/img/ image" +
                                imageCounter.ToString() + "." + extension;
                            try
                            {
                                imageInfo.Bitmap.Save(imageFileName, imageFormat);
                            }
                            catch (System.Runtime.InteropServices.ExternalException)
                            {
                                return null;
                            }
                            XElement img = new XElement(Xhtml.img,
                                new XAttribute(NoNamespace.src, imageFileName),
                                imageInfo.ImgStyleAttribute,
                                imageInfo.AltText != null ?
                                    new XAttribute(NoNamespace.alt, imageInfo.AltText) : null);
                            return img;
                        }
                    };
                    XElement html = HtmlConverter.ConvertToHtml(doc, settings);
                    File.WriteAllText(@"C:\Users\admin\Desktop\New Microsoft Word Document.html", html.ToStringNewLineOnAttributes());
                };
            }

transitional or strict format ?

$
0
0
Does anyone know how to determine if a given Open XML file is based on the transitional or strict format?
When I open a file in Word 2016 which was created in Word 2007 I get the “Compatibility Mode” notification. How can I figure this out by using Open XML SDK? I tried to compare file versions from 2007 (saved again in 2016, but still in compatibility format) and 2016 but only found slight differences in the settings and styles part. There is the app property AppVersion but it only shows which Office version was last used to save the file.

Jens H&#228;upel [MSFT]

Viewing all 1288 articles
Browse latest View live


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