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

Faster Find By Underline

$
0
0

Hello all,

I have a working piece of code that returns all Ranges that are underlined.
The problem is that it takes quite some time (30+ seconds) on 300+ page documents.  I'm hopeful there is a faster way to achieve the same goal perhaps using OpenXml maybe (not that good with OpenXml so need help there). 

Here is the working code:

public static List<Range> SearchByUnderline(Document document)
        {
            List<Range> ranges = new List<Range>();
            Word.Range selection = document.Content;

            selection.Find.ClearFormatting();
            selection.Find.Font.Underline = WdUnderline.wdUnderlineSingle;
            selection.Find.Execute();

            List<int> paragraphs = new List<int>();
            while (selection.Find.Found)
            {
                if (selection.Paragraphs.Count > 0)
                {
                    if (paragraphs.Where(w => w == selection.Paragraphs[1].Range.Start).Count() == 0)
                    {
                        paragraphs.Add(selection.Paragraphs[1].Range.Start);
                        ranges.Add(selection.Duplicate);
                    }
                }
                selection.Find.Execute();
            }

            return ranges;
        }

Thank you in advance!


Thank you,

Nick Metnik

Please mark my response as helpful if it has helped you in any way or as the answer if it is a valid solution.
Blog
LinkedIn


Latest Version of DocumentFormat.OpenXml.dll that could support content apps in PowerPoint (Office2013-SP1)

$
0
0

Hi,

I am looking for a latest version of Open XML SDK (above 2.5) which could support PowerPoint documents generation with content web apps contained within. I tried to use Open XML SDK ver-2.5, but it gives error on the following statement...

WebExtensionPart webExtensionPart1 = slidePart1.AddNewPart<WebExtensionPart>("rId2");
GenerateWebExtensionPart1Content(webExtensionPart1);

Thanks,


Asif


Program creates the document but generates an error. Is there a way to resolve the error or identify what it stems from? System.InvalidOperationException: Cannot insert the OpenXmlElement "newChild" because it is part of a tree.

$
0
0

Hi All,

I had been trying to find a way to add a header to my document that worked and seemed simple enough for me.  I found a solution and tried to modifiy it to work with my program.  I created a smaller test version in order to attempt determining how well it worked.  After testing, it generated an error and crashed, however it still created the word document the way I desired (basically a document with a header and body text).  I attempted adding try/catches but removed them as you'll see below because it would still crash and say my exception message variables were null unless I did not try to extract the message from the exception variable.  I am using Visual Web Developer 2013 and OpenXML 2.5.  Any help is appreciated, I've only been using the OpenXML for about 2 weeks.

Thank you,

Mitch

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
namespace HASPOnline
{
    public class TestDoc2
    {
        public TestDoc2()
        {
                string documentPath = @"C:\Users\me\Desktop\HeaderFooterDocument.docx";
                using (WordprocessingDocument package = WordprocessingDocument.Create(documentPath, WordprocessingDocumentType.Document))
                {
                        AddParts(package);
                        MainDocumentPart mainPart = package.MainDocumentPart;
                        Body body = package.MainDocumentPart.Document.Body;
                        Paragraph paraDocType = body.AppendChild(new Paragraph());
                        //Create run thats hold text that will be added to the paragraph
                        Run runDocHeader = paraDocType.AppendChild(new Run());
                        RunProperties rpDocHdr = new RunProperties();
                        rpDocHdr.Append(new Bold());
                        FontSize fs = new FontSize();
                        fs.Val = new StringValue("40");
                        rpDocHdr.Append(fs);
                        runDocHeader.AppendChild<RunProperties>(rpDocHdr);
                        //Add text to the run
                        runDocHeader.AppendChild(new Text("Health and Safety Plan"));
                        //Title Area
                        Paragraph paraHaspTitle = body.AppendChild(new Paragraph());
                        Run runTitle = paraHaspTitle.AppendChild(new Run());
                        RunProperties runproperties = runTitle.AppendChild(new RunProperties(new Bold()));
                        runTitle.AppendChild(new CarriageReturn());//Drop down a line
                        runTitle.AppendChild(new Bold());//Add bold to text
                        runTitle.AppendChild(new Text("Title: ") { Space = SpaceProcessingModeValues.Preserve });
                        //Title text
                        Run runTitleActual = paraHaspTitle.AppendChild(new Run());
                        runTitleActual.AppendChild(new Text("Will hold string variable for title here."));
                        //add body with more content back to document
                        mainPart.Document.Append(body);
                }
        }
        private static void AddParts(WordprocessingDocument parent)
        {
            string headerText = "HASP#:                                                                Expiration Date:";
                var mainDocumentPart = parent.AddMainDocumentPart();
                GenerateMainDocumentPart().Save(mainDocumentPart);
                var documentSettingsPart = mainDocumentPart.AddNewPart<DocumentSettingsPart>("rId1");
                GenerateDocumentSettingsPart().Save(documentSettingsPart);
                var firstPageHeaderPart = mainDocumentPart.AddNewPart<HeaderPart>("rId2");
                GeneratePageHeaderPart(headerText).Save(firstPageHeaderPart);
                var evenPageHeaderPart = mainDocumentPart.AddNewPart<HeaderPart>("rId4");
                GeneratePageHeaderPart(headerText).Save(evenPageHeaderPart);
                var oddPageheaderPart = mainDocumentPart.AddNewPart<HeaderPart>("rId6");
                GeneratePageHeaderPart(headerText).Save(oddPageheaderPart);
        }
        private static Document GenerateMainDocumentPart()
        {
            var element =
                new Document(
                    new Body(
                        new SectionProperties(
                            new HeaderReference()
                            {
                                Type = HeaderFooterValues.First,
                                Id = "rId2"
                            },
                            new HeaderReference()
                            {
                                Type = HeaderFooterValues.Even,
                                Id = "rId4"
                            },
                            new HeaderReference()
                            {
                                Type = HeaderFooterValues.Default,
                                Id = "rId6"
                            },
                            new PageMargin()
                            {
                                Top = 1440,
                                Right = (UInt32Value)1440UL,
                                Bottom = 1440,
                                Left = (UInt32Value)1440UL,
                                Header = (UInt32Value)720UL,
                                Footer = (UInt32Value)720UL,
                                Gutter = (UInt32Value)0UL
                            },
                            new TitlePage()
                        )));
            return element;
        }
        private static Header GeneratePageHeaderPart(string HeaderText)
        {
            var element =
                new Header(
                    new Paragraph(
                        new ParagraphProperties(
                            new ParagraphStyleId() { Val = "Header" }),
                        new Run(
                            new Text(HeaderText))
                    ));
            return element;
        }
        private static Settings GenerateDocumentSettingsPart()
        {
            var element =
                new Settings(new EvenAndOddHeaders());
            return element;
        }
    }
}


Creating documents using the Open XML SDK 2.5 - Problem with many WordprocessingShapes

$
0
0

I am programmatically creating a Word 2013(and 2010,2007) document. This contains many WordprocessingShape groups, each group containing a text box and up to 4 lines. I can always open the documents I create and they pass the SDK validation test. Over a certain number of groups I get an error message 'a file error has occurred' when I try to save the document (or make a modification and save).

I raised a tech support incident over 8 days ago using my MSDN subscription but have had no response as yet. Hopefully I will have more luck here........!

I originally asked this in the Word Developers forum but have been directed here as more appropriate


Steve Booth

Embedding Documents/Object in Word by Using the Open XML SDK

$
0
0

Hi,

With the help of following link "http://msdn.microsoft.com/en-ca/library/ee355229.aspx" i am able to embed documents in word successfully. After inserting the document as object i have to mention the file name for the object. Is there any way to mention the Object name using code?. 

And if i try to insert more than one object (different files) in document it shows the second object as image. How to insert more than one object in word document?.

Thanks in advance :)

New vs Existing worksheets

$
0
0

I wanted to use the code at this link to add strings to multiple "existing cells" on an "existing sheet". I want to get away from creating new sheets every time I use this code to export a table of strings from my database into my excel report sheet template. Is there a way to modify the code to do overwrites and write many cells at once? I tried for instance naming the sheet without the id number added but that just creates a sheet with the same name that excel then identifies as material to be recovered and it changes the sheet name to something to prevent duplicates. It feels like the code blocks defining the new worksheet and cell locations would have to be changed a lot so I am not sure if this kind of functionality is possible. I would appreciate any pointers to the right solution.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
//first "Add Reference" "Assemblies" named "DocumentFormat.OpenXml" and "WindowsBase"
//needed for using the open xml sdk to insert cells into spreadsheet
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
//added this to allow the process statement that opens excel
using System.Diagnostics;

namespace Inserting_cells_into_spreadsheet
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            GeneratedClass gc = new GeneratedClass();
            gc.InsertText(@"C:\Users\Jordan Walker\Documents\DATA sheets\MAR.xlsx", "Hello New World");
            //This opens the excel file from the current directory
            Process.Start(@"C:\Users\Jordan Walker\Documents\DATA sheets\MAR.xlsx");
        }
    }
}
namespace Inserting_cells_into_spreadsheet
{
    public class GeneratedClass
    {
        // Given a document name and text,
        // inserts a new worksheet and writes the text to cell "A1" of the new worksheet.
        public void InsertText(string docName, string text)
        {
            // Open the document for editing.
            using (SpreadsheetDocument spreadSheet = SpreadsheetDocument.Open(docName, true))
            {
                // Get the SharedStringTablePart. If it does not exist, create a new one.
                SharedStringTablePart shareStringPart;
                if (spreadSheet.WorkbookPart.GetPartsOfType<SharedStringTablePart>().Count() > 0)
                {
                    shareStringPart = spreadSheet.WorkbookPart.GetPartsOfType<SharedStringTablePart>().First();
                }
                else
                {
                    shareStringPart = spreadSheet.WorkbookPart.AddNewPart<SharedStringTablePart>();
                }

                // Insert the text into the SharedStringTablePart.
                int index = InsertSharedStringItem(text, shareStringPart);
                
                // Insert a new worksheet.
                WorksheetPart worksheetPart = InsertWorksheet(spreadSheet.WorkbookPart);
                
                // Insert cell A1 into the new worksheet.
                Cell cell = InsertCellInWorksheet("A", 1, worksheetPart);

                // Set the value of cell A1.
                cell.CellValue = new CellValue(index.ToString());
                cell.DataType = new EnumValue<CellValues>(CellValues.SharedString);

                // Save the new worksheet.
                worksheetPart.Worksheet.Save();

            }
        }

        // Given text and a SharedStringTablePart, creates a SharedStringItem with the specified text 
        // and inserts it into the SharedStringTablePart. If the item already exists, returns its index.
        private static int InsertSharedStringItem(string text, SharedStringTablePart shareStringPart)
        {
            // If the part does not contain a SharedStringTable, create one.
            if (shareStringPart.SharedStringTable == null)
            {
                shareStringPart.SharedStringTable = new SharedStringTable();
            }

            int i = 0;

            // Iterate through all the items in the SharedStringTable. If the text already exists, return its index.
            foreach (SharedStringItem item in shareStringPart.SharedStringTable.Elements<SharedStringItem>())
            {
                if (item.InnerText == text)
                {
                    return i;
                }

                i++;
            }

            // The text does not exist in the part. Create the SharedStringItem and return its index.
            shareStringPart.SharedStringTable.AppendChild(new SharedStringItem(new DocumentFormat.OpenXml.Spreadsheet.Text(text)));
            shareStringPart.SharedStringTable.Save();

            return i;
        }

        // Given a WorkbookPart, inserts a new worksheet.
        private static WorksheetPart InsertWorksheet(WorkbookPart workbookPart)
        {
            // Add a new worksheet part to the workbook.
            WorksheetPart newWorksheetPart = workbookPart.AddNewPart<WorksheetPart>();
            newWorksheetPart.Worksheet = new Worksheet(new SheetData());
            newWorksheetPart.Worksheet.Save();

            Sheets sheets = workbookPart.Workbook.GetFirstChild<Sheets>();
            string relationshipId = workbookPart.GetIdOfPart(newWorksheetPart);

            // Get a unique ID for the new sheet.
            uint sheetId = 1;
            if (sheets.Elements<Sheet>().Count() > 0)
            {
                sheetId = sheets.Elements<Sheet>().Select(s => s.SheetId.Value).Max() + 1;
            }

            string sheetName = "Sheet" + sheetId;

            // Append the new worksheet and associate it with the workbook.
            Sheet sheet = new Sheet() { Id = relationshipId, SheetId = sheetId, Name = sheetName };
            sheets.Append(sheet);
            workbookPart.Workbook.Save();

            return newWorksheetPart;
        }

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

            // If the worksheet does not contain a row with the specified row index, insert one.
            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 there is not a cell with the specified column name, insert one.  
            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
            {
                // Cells must be in sequential order according to CellReference. Determine where to insert the new cell.
                Cell refCell = null;
                foreach (Cell cell in row.Elements<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;
            }
        }
    }    
}

Can't add sheet to existing Excel spread sheet

$
0
0

I am using the following code to try add another sheet to an existing excel file...

		Dim workBookPart As WorkbookPart = spreadsheetdoc.AddWorkbookPart()

This code works fine for inserting the first sheet, but throws "Only one instance of the type is allowed for this parent" when there is already an existing sheet.

Am I misunderstanding something?

Please help.



http://sites.google.com/site/carrollsoftware/products/task-manager

Can you show a way to for a Word document to begin with the page orientation in default/portrait and end in landscape within the same document?

$
0
0

I am trying to create a word document to that changes to landscape after reaching a certain point.  I have added a page break and changed the page orientation to landscape, however the entire document becomes landscape and not the ending portion.  I am not sure of the best approach for this issue.  I have attached a shortened version of my code to demonstrate my intentions.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
namespace HASPOnline
{
    public class TestDoc2
    {
        public TestDoc2()
        {
                string documentPath = @"C:\Users\me\Desktop\PageOrientationTest.docx";
                using (WordprocessingDocument package = WordprocessingDocument.Create(documentPath, WordprocessingDocumentType.Document))
                {
                    AddParts(package);
                    MainDocumentPart mainPart = package.MainDocumentPart;
                    Body body = package.MainDocumentPart.Document.Body;
                    //body.Append(PageOrientationPortrait());
                    Paragraph paraDocType = body.AppendChild(new Paragraph());
                    //Create run thats hold text that will be added to the paragraph
                    Run runDocHeader = paraDocType.AppendChild(new Run());
                    RunProperties rpDocHdr = new RunProperties();
                    rpDocHdr.Append(new Bold());
                    FontSize fs = new FontSize();
                    fs.Val = new StringValue("40");
                    rpDocHdr.Append(fs);
                    runDocHeader.AppendChild<RunProperties>(rpDocHdr);
                    //Add text to the run
                    runDocHeader.AppendChild(new Text("Health and Safety Plan"));
                    //Title Area
                    Paragraph paraHaspTitle = body.AppendChild(new Paragraph());
                    Run runTitle = paraHaspTitle.AppendChild(new Run());
                    RunProperties runproperties = runTitle.AppendChild(new RunProperties(new Bold()));
                    runTitle.AppendChild(new CarriageReturn());//Drop down a line
                    runTitle.AppendChild(new Bold());//Add bold to text
                    runTitle.AppendChild(new Text("Title: ") { Space = SpaceProcessingModeValues.Preserve });
                    //Title text
                    Run runTitleActual = paraHaspTitle.AppendChild(new Run());
                    runTitleActual.AppendChild(new Text("Will hold string variable for title here."));
                    //Insert Page Break here
                    Paragraph pageBreakParagraph1 = new Paragraph(new Run(new Break() { Type = BreakValues.Page }));
                    body.Append(pageBreakParagraph1);
                    //Change to Landscape Orientation here
                    body.Append(PageOrientationLandScape());
                    //Add Paragraph
                    Paragraph paraTest = CreatePara(); 
                    body.Append(paraTest);
                }
        }
        private static Paragraph CreatePara()
        {
            Paragraph para1 = new Paragraph();
            Run run1 = new Run(new Text("This is a paragraph."));
            para1.Append(run1);
            return para1;
        }
        private static SectionProperties PageOrientationPortrait()
        {
            SectionProperties sectionProperties2 = new SectionProperties();
            PageSize pageSize = new PageSize()
            {
                Width = (UInt32Value)12240U,
                Height = (UInt32Value)15840U,
                Orient = PageOrientationValues.Portrait
            };
            PageMargin pageMargin = new PageMargin()
            {
                Top = 1440,
                Right = (UInt32Value)1440U,
                Bottom = 1440,
                Left = (UInt32Value)1440U,
                Header = (UInt32Value)720U,
                Footer = (UInt32Value)720U,
                Gutter = (UInt32Value)0U
            };
            Columns columns = new Columns() { Space = "720" };
            DocGrid docGrid = new DocGrid() { LinePitch = 360 };
            sectionProperties2.Append(pageSize, pageMargin, columns, docGrid);
            return sectionProperties2;
        }
        private static SectionProperties PageOrientationLandScape()
        {
            SectionProperties sectionProperties = new SectionProperties();
            PageSize pageSize = new PageSize()
            {
                Width = (UInt32Value)15840U,
                Height = (UInt32Value)12240U,
                Orient = PageOrientationValues.Landscape
            };
            PageMargin pageMargin = new PageMargin()
            {
                Top = 1440,
                Right = (UInt32Value)1440U,
                Bottom = 1440,
                Left = (UInt32Value)1440U,
                Header = (UInt32Value)720U,
                Footer = (UInt32Value)720U,
                Gutter = (UInt32Value)0U
            };
            Columns columns = new Columns() { Space = "720" };
            DocGrid docGrid = new DocGrid() { LinePitch = 360 };
            sectionProperties.Append(pageSize, pageMargin, columns, docGrid);
            return sectionProperties;
        }
        private static void AddParts(WordprocessingDocument parent)
        {
            string headerText = "HASP#:                                                                Expiration Date:";
                var mainDocumentPart = parent.AddMainDocumentPart();
                GenerateMainDocumentPart().Save(mainDocumentPart);
                var documentSettingsPart = mainDocumentPart.AddNewPart<DocumentSettingsPart>("rId1");
                GenerateDocumentSettingsPart().Save(documentSettingsPart);
                var firstPageHeaderPart = mainDocumentPart.AddNewPart<HeaderPart>("rId2");
                GeneratePageHeaderPart(headerText).Save(firstPageHeaderPart);
                var evenPageHeaderPart = mainDocumentPart.AddNewPart<HeaderPart>("rId4");
                GeneratePageHeaderPart(headerText).Save(evenPageHeaderPart);
                var oddPageheaderPart = mainDocumentPart.AddNewPart<HeaderPart>("rId6");
                GeneratePageHeaderPart(headerText).Save(oddPageheaderPart);
        }
        private static Document GenerateMainDocumentPart()
        {
            var element =
                new Document(
                    new Body(
                        new SectionProperties(
                            new HeaderReference()
                            {
                                Type = HeaderFooterValues.First,
                                Id = "rId2"
                            },
                            new HeaderReference()
                            {
                                Type = HeaderFooterValues.Even,
                                Id = "rId4"
                            },
                            new HeaderReference()
                            {
                                Type = HeaderFooterValues.Default,
                                Id = "rId6"
                            },
                            new PageMargin()
                            {
                                Top = 1440,
                                Right = (UInt32Value)1440UL,
                                Bottom = 1440,
                                Left = (UInt32Value)1440UL,
                                Header = (UInt32Value)720UL,
                                Footer = (UInt32Value)720UL,
                                Gutter = (UInt32Value)0UL
                            },
                            new TitlePage()
                        )));
            return element;
        }
        private static Header GeneratePageHeaderPart(string HeaderText)
        {
            var element =
                new Header(
                    new Paragraph(
                        new ParagraphProperties(
                            new ParagraphStyleId() { Val = "Header" }),
                        new Run(
                            new Text(HeaderText))
                    ));
            return element;
        }
        private static Settings GenerateDocumentSettingsPart()
        {
            var element =
                new Settings(new EvenAndOddHeaders());
            return element;
        }
    }
}

Any help is appreciated.

Thank you,

Mitch


How to generate Word document programmatically from template and data?

$
0
0

I’m tasked with the server side Word Document generation and need advice what approach to take. Users should be able to create template documents (using Word, not using Visual Studio) and then my C# class library should fill those templates with data (texts, images, table rows). Can I use Content Controls to style the text or table and then use the code to fill in actual text or table rows?

 

Is there a sample how to generate a table this way?

I also don’t understand how do I feed the image into Image Content Control programmatically.

Once again - I must not generate the whole document content, instead I need to fill in pre-styled placeholders to give users ability to restyle the template with Word.


Thank you! Konstantin

AddAltChunkHTML to DOCX Inserts BOM

$
0
0

I am inserting html text into a docx word document. All works okay except the end result docx file has a BOM at the beginning of the document.xml. I do not understand this although I suspect an encoding issue. Example code below. Would appreciate anyone's thoughts on this.

        void AddAltChunkHTML(MainDocumentPart mainPart, Word.SdtElement sdt, SPFile filename)
        {
            string altChunkId = "AltChunkId" + id;
            id++;
            // read insert data
            byte[] byteArray = filename.OpenBinary();

            AlternativeFormatImportPart chunk = mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.Xhtml, altChunkId);

            // load the insert data into the chunk
            using (MemoryStream mem = new MemoryStream())
            {
                mem.Write(byteArray, 0, (int)byteArray.Length);
                mem.Seek(0, SeekOrigin.Begin);
                chunk.FeedData(mem);
            }

            Word.AltChunk altChunk = new Word.AltChunk();
            altChunk.Id = altChunkId;
            //Replace content control with altChunk information

            OpenXmlElement parent = sdt.Parent;
            parent.InsertAfter(altChunk, sdt);
            sdt.Remove();
        }

OpenXML Excel file, works in Excel 2007, OpenOffice, etc but not in Excel 2010

$
0
0

Hi everyone,

I have a problem.  I host a free website, sharing source code and ideas with other developers.  One of my projects is a very simple C# class, which generates an Excel 2007 .xlsx file.  All source code is provided, along with a demo showing how to use it, free of charge.  No registration required.

http://www.mikesknowledgebase.com/pages/CSharp/ExportToExcel.htm

The .xlsx files that this class generates are fine, they open in Excel 2007 & OpenOffice, I've run the OpenXmlValidatoron the files, and there are no reported problems.

However, If I open the file in Excel 2010 (with SP1), it opens, but if I go to the Print or Print Preview screen, Excel 2010 crashes.  

Googling around, I've found that many many users have experienced problems with HP print drivers, I followed some suggestions, such as turning off multi-threading in Excel, but it makes no difference.  I tried setting the default printer as the "Microsoft XPS Document Writer", but it made no difference.

Here is a copy of the Excel file that my demo produces (and which crashes Excel 2010).   Can someone tell me why it opens okay, but then crashes Excel 2010 ?  

http://www.MikesKnowledgeBase.com/SampleCode/Sample.xlsx

I can get around the problem by loading this file in Excel 2010, saving it as an ".xls" file (!!) and re-loading that... but it kinda defeats the purpose.

And, more generally, why does Excel 2007, OpenOffice and the OpenXmlValidator consider it to be in the correct format, but it crashes Excel 2010 ?  I'm surprised that Excel 2010 doesn't at least attempt to report some kind of problem with the Excel file, rather than bombing out.

Mike


Formulas and equations not getting converted while html conversion

$
0
0

Hi,

Am converting SomeFile.docx to SomeFile.html from Docx to Html using the below code, in this code, am able to get images but formulas and equations are not getting as images while conversion to html, how can i accomplish this getting formulas and equations as images while conversion?

 using (WordprocessingDocument doc = WordprocessingDocument.Open(WordFilePath, true))
                    {
                        HtmlConverterSettings settings = new HtmlConverterSettings()
                        {
                            PageTitle = "My Page Title"
                        };
                        html = HtmlConverter.ConvertToHtml(doc, settings,
                                    imageInfo =>
                                    {
                                        System.IO.DirectoryInfo localDirInfo = new System.IO.DirectoryInfo(imageDirectoryName);
                                        if (!localDirInfo.Exists)
                                            localDirInfo.Create();
                                        //++imageCounter;
                                        string extension = imageInfo.ContentType.Split('/')[1].ToLower();
                                        System.Drawing.Imaging.ImageFormat imageFormat = null;
                                        switch (extension.ToLower())
                                        {
                                            case "png":
                                                imageFormat = System.Drawing.Imaging.ImageFormat.Png;
                                                break;
                                            case "bmp":
                                                imageFormat = System.Drawing.Imaging.ImageFormat.Bmp;
                                                break;
                                            case "jpeg":
                                                imageFormat = System.Drawing.Imaging.ImageFormat.Jpeg;
                                                break;
                                            case "tiff":
                                                imageFormat = System.Drawing.Imaging.ImageFormat.Tiff;
                                                break;
                                            default:
                                                imageFormat = System.Drawing.Imaging.ImageFormat.Jpeg;
                                                break;
                                        }
                                        // If the image format is not one that you expect, ignore it,
                                        // and do not return markup for the link.
                                        if (imageFormat == null)
                                            return null;

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



Best Regards, -------------- Mohammed Nayeem Senior Software Engineer


Inserting an image into an Excel Spreadsheet: Part Deux

$
0
0

I was having a terrible time figuring out how to place an image on an Excel spreadsheet using the OpenXML SDK.  Finally, I found this terribly complicated code sample on the internet somewhere that seems to get the job done.

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml.Validation;
using DocumentFormat.OpenXml.Drawing.Spreadsheet;

using System.IO;
using System.Drawing;

namespace ConsoleApplication4
{
    class Program
    {
        static void Main(string[] args)
        {
            string sFile = "ExcelOpenXmlWithImage.xlsx";
            if (File.Exists(sFile))
            {
                File.Delete(sFile);
            }
            BuildWorkbook(sFile);
        }

        private static void BuildWorkbook(string filename)
        {
            try
            {
                using (SpreadsheetDocument xl = SpreadsheetDocument.Create(filename, SpreadsheetDocumentType.Workbook))
                {
                    WorkbookPart wbp = xl.AddWorkbookPart();
                    WorksheetPart wsp = wbp.AddNewPart<WorksheetPart>();                                
                    Workbook wb = new Workbook();
                    FileVersion fv = new FileVersion();
                    fv.ApplicationName = "Microsoft Office Excel";
                    Worksheet ws = new Worksheet();
                    SheetData sd = new SheetData();

                    //string sImagePath = "polymathlogo.png";
                    string sImagePath = @"c:\temp\chartImg.png";
                    DrawingsPart dp = wsp.AddNewPart<DrawingsPart>();
                    ImagePart imgp = dp.AddImagePart(ImagePartType.Png, wsp.GetIdOfPart(dp));
                    using (FileStream fs = new FileStream(sImagePath, FileMode.Open))
                    {
                        imgp.FeedData(fs);
                    }

                    NonVisualDrawingProperties nvdp = new NonVisualDrawingProperties();
                    nvdp.Id = 1025;
                    nvdp.Name = "Picture 1";
                    nvdp.Description = "polymathlogo";
                    DocumentFormat.OpenXml.Drawing.PictureLocks picLocks = new DocumentFormat.OpenXml.Drawing.PictureLocks();
                    picLocks.NoChangeAspect = true;
                    picLocks.NoChangeArrowheads = true;
                    NonVisualPictureDrawingProperties nvpdp = new NonVisualPictureDrawingProperties();
                    nvpdp.PictureLocks = picLocks;
                    NonVisualPictureProperties nvpp = new NonVisualPictureProperties();
                    nvpp.NonVisualDrawingProperties = nvdp;
                    nvpp.NonVisualPictureDrawingProperties = nvpdp;

                    DocumentFormat.OpenXml.Drawing.Stretch stretch = new DocumentFormat.OpenXml.Drawing.Stretch();
                    stretch.FillRectangle = new DocumentFormat.OpenXml.Drawing.FillRectangle();                   

                    BlipFill blipFill = new BlipFill();
                    DocumentFormat.OpenXml.Drawing.Blip blip = new DocumentFormat.OpenXml.Drawing.Blip();
                    blip.Embed = dp.GetIdOfPart(imgp);
                    blip.CompressionState = DocumentFormat.OpenXml.Drawing.BlipCompressionValues.Print;
                    blipFill.Blip = blip;
                    blipFill.SourceRectangle = new DocumentFormat.OpenXml.Drawing.SourceRectangle();
                    blipFill.Append(stretch);

                    DocumentFormat.OpenXml.Drawing.Transform2D t2d = new DocumentFormat.OpenXml.Drawing.Transform2D();
                    DocumentFormat.OpenXml.Drawing.Offset offset = new DocumentFormat.OpenXml.Drawing.Offset();
                    offset.X = 1000;
                    offset.Y = 1000;
                    t2d.Offset = offset;
                    Bitmap bm = new Bitmap(sImagePath);
                    //http://en.wikipedia.org/wiki/English_Metric_Unit#DrawingML
                    //http://stackoverflow.com/questions/1341930/pixel-to-centimeter
                    //http://stackoverflow.com/questions/139655/how-to-convert-pixels-to-points-px-to-pt-in-net-c
                    DocumentFormat.OpenXml.Drawing.Extents extents = new DocumentFormat.OpenXml.Drawing.Extents();
                    extents.Cx = (long)bm.Width * (long)((float)914400 / bm.HorizontalResolution);
                    extents.Cy = (long)bm.Height * (long)((float)914400 / bm.VerticalResolution);
                    bm.Dispose();
                    t2d.Extents = extents;
                    ShapeProperties sp = new ShapeProperties();
                    sp.BlackWhiteMode = DocumentFormat.OpenXml.Drawing.BlackWhiteModeValues.Auto;
                    sp.Transform2D = t2d;
                    DocumentFormat.OpenXml.Drawing.PresetGeometry prstGeom = new DocumentFormat.OpenXml.Drawing.PresetGeometry();
                    prstGeom.Preset = DocumentFormat.OpenXml.Drawing.ShapeTypeValues.Rectangle;
                    prstGeom.AdjustValueList = new DocumentFormat.OpenXml.Drawing.AdjustValueList();
                    sp.Append(prstGeom);
                    sp.Append(new DocumentFormat.OpenXml.Drawing.NoFill());

                    DocumentFormat.OpenXml.Drawing.Spreadsheet.Picture picture = new DocumentFormat.OpenXml.Drawing.Spreadsheet.Picture();
                    picture.NonVisualPictureProperties = nvpp;
                    picture.BlipFill = blipFill;
                    picture.ShapeProperties = sp;

                    Position pos = new Position();
                    pos.X =(Int64) 1000;
                    pos.Y =(Int64) 1000;
                    Extent ext = new Extent();
                    ext.Cx = extents.Cx;
                    ext.Cy = extents.Cy;
                    AbsoluteAnchor anchor = new AbsoluteAnchor();
                    anchor.Position = pos;
                    anchor.Extent = ext;
                    anchor.Append(picture);
                    anchor.Append(new ClientData());
                    WorksheetDrawing wsd = new WorksheetDrawing();
                    wsd.Append(anchor);
                    Drawing drawing = new Drawing();
                    drawing.Id = dp.GetIdOfPart(imgp);

                    wsd.Save(dp);                   

                    ws.Append(sd);
                    ws.Append(drawing);
                    wsp.Worksheet = ws;
                    wsp.Worksheet.Save();
                    Sheets sheets = new Sheets();
                    Sheet sheet = new Sheet();
                    sheet.Name = "Sheet1";
                    sheet.SheetId = 1;
                    sheet.Id = wbp.GetIdOfPart(wsp);
                    sheets.Append(sheet);
                    wb.Append(fv);
                    wb.Append(sheets);

                    xl.WorkbookPart.Workbook = wb;
                    xl.WorkbookPart.Workbook.Save();
                    xl.Close();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                Console.ReadLine();
            }
        }
    }
}

 

I can hardly make heads or tails out of this code sample.  However, the next thing that I want to do is to place the image at a specific point on the spreadsheet and insert some numerical data into the cells.

I have written some code that inserts numeric data into the cells, but when I try to combine it with this code to insert an image, strange exceptions are thrown.  Furthermore, try as I may to change the "position" and "offset" elements in the code, the image always appears in the upper-left hand corner of the spreadsheet.

How do I make this code place the image at an arbitrary point in my spreadsheet and how do I add some numeric data in the cells of the spreadsheet.

How to save Word as PDF using Open XML SDK 2.0

$
0
0

How do we use Open XML SDK 2.0 to save word files as a PDF? 


Thomas Abruzzo thomas@tampsystems.com

Bar3DChart Scaling

$
0
0

I am creating some embedded Bar3DChart elements using OpenXML and PowerPoint. The scale of the chart on the left wall is as expected auto changing based on the embedded data of the chart.  I have several charts and want them all to be 0 to 25 regardless of the data. I assume that what I am looking for is in the OpenXml.Drawing.Charts.Scaling object, but I have not been able to find that element in my chart object.

I have been able to successfully display the chart using data from a database list and even permanently change the underlying Excel spreadsheet, so I have made considerable progress.



Modify font style, merge cells and coloring cells using Open XML sdk

$
0
0

Hi,

  I am using OpenXML SDK for read excel file, modify the contents and save it in to a folder in C#

  Requirement 1:  First column to be in bold

  Requirement 2: Make different colors for cell1, cell2 , cell3 etc... ofRow2

                            Eg: Cell1 (Green), Cell2 (Yellow), Cell3 (Red), Cell4(Pink) etc... ofRow 2

  Requirement 3:  Merge two adjascent cells

  Note: I have 3 sheets in a workbook and to do the modification only in second sheet,                         Following is the code and to make the above said changes in object 'sheetData' of the following code.

                using (SpreadsheetDocument spreadSheetDocument = SpreadsheetDocument.Open(stream, true))
                {
                    WorkbookPart workBookPart = spreadSheetDocument.WorkbookPart;
                    IEnumerable<Sheet> sheets = workBookPart.Workbook.GetFirstChild<Sheets>().Elements<Sheet>().Where(s => s.Name == "Sheet2");
                    if (sheets.Count() == 0)
                    {
                        return;
                    }

                    string relationshipId = sheets.First().Id.Value;
                    WorksheetPart worksheetPart = (WorksheetPart)workBookPart.GetPartById(relationshipId);
                    Worksheet workSheet = worksheetPart.Worksheet;
                    SheetData sheetData = workSheet.GetFirstChild<SheetData>();
                    IEnumerable<Row> rows = sheetData.Descendants<Row>();
                    .......

           

                 Please help me to achieve this.

     Thanks in advance.

 

Error while opening OpenXML docx file - The specified package is invalid. The main part is missing.

$
0
0

Hello,

I have a problem with opening some docx files using the following code. I get the error that " The specified package is invalid. The main part is missing."

using (WordprocessingDocument wdDoc = WordprocessingDocument.Open(docName, true))

I have seen people having this issue in the internet and the solution was related to the permissions. This however doesn't seem to be the case here, because I put the files in the same folder, and some of them work, some of them don't.

I don't know where exactly is the problem - please help me identify the issue. 

This is the document.xml file from the file that does not work:

http://pastebin.com/sKy99YTC

This is the document.xml file from a working file:

http://pastebin.com/1T4z8wx9



Bartosz

OpenXMLWriter Performance Issue while writing large excel file. (35000 rows and 100 cells)

$
0
0

Hi,

Writing an large excel file using SpreadsheetDocument takes around 2 mins.

surprisingly when i comment the cell.Datatype line the excel file generates in 10 secs. But in this case opening in excel it gives error as datatype must be specified for string data.

1. Can Datatype be specified for entire column?

2. Can we avoid specifying Datatype somehow? 

Please let me know if the performance of the code can be improved some how.

In the sample code I am using same text value for each cell but in my project their will be different values for each cell . Thus I cant use sharedtables.

My code is as follows.

static void Main(string[] args)
        {
            String str_IntermidiateXMLPath = "c:\\Ouput.xlsx";
            File.Copy("c:\\book.xlsx", str_IntermidiateXMLPath, true);
            using (SpreadsheetDocument SpreadsheetDocumentObj = SpreadsheetDocument.Open(
                        str_IntermidiateXMLPath, true))
            {
                WorkbookPart workbookpart = null;
                WorksheetPart worksheetpart = null;
                Worksheet worksheet = null;
                SheetData sheetdata = null;
                OpenXmlWriter writer = null;
                Cell cell = null;
                Row row = null;

                SpreadsheetDocumentObj.CompressionOption = CompressionOption.SuperFast;
                workbookpart    = SpreadsheetDocumentObj.WorkbookPart;
                worksheetpart   = workbookpart.WorksheetParts.First();

                writer = OpenXmlWriter.Create(worksheetpart);
                writer.WriteStartElement(new Worksheet());
                writer.WriteStartElement(new SheetData());
                
                for (int i = 0; i < 35000; i++)
                {
                    row = new Row();
                    for (int j = 0; j < 100; j++)
                    {
                        cell = new Cell();
                        row.Append(cell);

                       cell.DataType = CellValues.InlineString;
                       cell.InlineString = new InlineString { Text = new Text { Text = "Hi" } };
                    }

                    writer.WriteElement(row);
                }
                

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

IDENTIFY CHARTSHEETS OPEN XML SDK

$
0
0

I am looking for a way to identify if an Excel sheet is a WorkSheet or a ChartSheet, in the below when it executes the last line, it will throw an exception if the sheet is a ChartSheet. Is there a way to identify the type of sheet using the Sheet.Id?

            Using SDocument As SpreadsheetDocument = SpreadsheetDocument.Open(filename, False)
                Dim workbookPart As WorkbookPart = SDocument.WorkbookPart
                workbookPart.Workbook.Descendants(Of Sheet)()
                For Each Sheet As Sheet In SDocument.WorkbookPart.Workbook.Sheets
                    Try
                        Dim sID As String = Sheet.Id
                        Console.WriteLine(sID)
                        Dim part As WorksheetPart = workbookPart.GetPartById(sID)

                        

How to identify if an Excel sheet is a WorkSheet or a ChartSheet

$
0
0

I am looking for a way to identify if an Excel sheet is a WorkSheet or a ChartSheet, in the below when it executes the last line, it will throw an exception if the sheet is a ChartSheet. Is there a way to identify the type of sheet using the Sheet.Id?

            Using SDocument As SpreadsheetDocument = SpreadsheetDocument.Open(filename, False)
                Dim workbookPart As WorkbookPart = SDocument.WorkbookPart
                workbookPart.Workbook.Descendants(Of Sheet)()
                For Each Sheet As Sheet In SDocument.WorkbookPart.Workbook.Sheets
                    Try
                        Dim sID As String = Sheet.Id
                        Console.WriteLine(sID)
                        Dim part As WorksheetPart = workbookPart.GetPartById(sID)

Viewing all 1288 articles
Browse latest View live


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