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

Cannot insert the OpenXmlElement "newChild" because it is part of a tree.

$
0
0

hi,

am getting this error(Cannot insert the OpenXmlElement "newChild" because it is part of a tree.) when i try to give border values to the table.

here is my code,

if

(sValue =="")

{

InsideVerticalBorder insideVBorder =newInsideVerticalBorder();

insideVBorder.Val =

newEnumValue<BorderValues>(BorderValues.None);

tblBorders.AppendChild(insideVBorder);

}

else

{

InsideVerticalBorder insideVBorder =newInsideVerticalBorder();

insideVBorder.Val =

newEnumValue<BorderValues>(BorderValues.Single);

tblBorders.AppendChild(insideVBorder);

}


banupriya


How to change the header and footer in the Section Breaks Next Page using OpenXML?

$
0
0

I have a word document file in which I added a Section Break of Next Page, now I want to change the header and footer of that page.

Scenario of example, I have a doc file which has four pages with headers and footers and added fifth page in the section break next page, I want to change the header and footer of the fifth page only. This is achievable manually by deselecting the Link to Previous button in the Word Application but I don't know how to change it using XML?

My code that adds the new page in the section breaks is:

class Program
	{
		static void Main(string[] args)
		{

			string path = @"C:\Riyaz\sample.docx";
			string strtxt = "Hello This is done by programmatically";

		   OpenAndAddTextToWordDocument(path,strtxt);
		}
		public static void OpenAndAddTextToWordDocument(string filepath, string txt)
		{

			using (DocX document = DocX.Load(@"C:\Riyaz\sample.docx"))
			{
				document.InsertSectionPageBreak();
				Paragraph p1 = document.InsertParagraph();
				p1.Append("This is new section");
				document.Save();
			}
		}
	}

Please help.

MemoryStream and WordprocessingDocument

$
0
0

Hi Everyone, 

 I have a problem when using the WordProcessingDocument object together with a MemoryStream object. 

 My code is the following. 

MemoryStream stream = new MemoryStream(loanDocumentViewModel.DocumentContent);

            //using (MemoryStream stream = new MemoryStream(data)) //;MemoryStream ms = new MemoryStream(dc.DocumentContent))
            //{
            using (WordprocessingDocument doc = WordprocessingDocument.Open(stream, true))
            //using (WordprocessingDocument doc = WordprocessingDocument.Open(@"Documents\OtherDocuments\copy.docx", true))
            {

              DocumentSettingsPart docSett = doc.MainDocumentPart.DocumentSettingsPart;
                docSett.RootElement.Append(new DocumentProtection { Edit = DocumentProtectionValues.ReadOnly });
                docSett.RootElement.Save();

                doc.MainDocumentPart.Document.Save();
            }

The dc.DocumentContent is a Array readed from a Database. 

When I save my object into the Database again and open it. 

   Word is telling me that the file is corrupt, but It can be opened. 

Any clues on what wrong with the code?

I have tried to do the same operation, with a plain file and that works perfectly. 

Best Regards

  Lars 

lastRenderedPageBreak and columns problem

$
0
0

I need to be able to identify specific pages in a Word doc by parsing the document.xml. I thought I could use the lastRenderedPageBreak to find the end of a page, and this seems to work in a single column layout. However, if I change the doc layout to two column layout, the lastRenderedPageBreak appears twice in a single page. This is further complicated by adding a Textbox to the Word doc - if the text box overlaps the column border then lastRenderedPageBreak will only appear once for that two column page. Therefore, it would seem that lastRenderedPageBreak is not suitable for identifying pages in document.xml.

Can anyone advise on a better way to identify specific pages in document.xml? I am using Word 2007.

Thanks.

Not able to implement Open XML SAX type approach in c#

$
0
0

My requirement is to export huge records with rows equal to 5 lakhs. I was using OpenXml approach like this :


 public void ExportCheck(DataSet ds, string destination)
        {
            using (var workbook = SpreadsheetDocument.Create(destination, 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();
               
                foreach (System.Data.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);
                    
                    uint sheetId = 1;
                    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 = table.TableName };
                    sheets.Append(sheet);               

                    DocumentFormat.OpenXml.Spreadsheet.Row emptyRow = new DocumentFormat.OpenXml.Spreadsheet.Row();

                     DocumentFormat.OpenXml.Spreadsheet.Row colRow = new DocumentFormat.OpenXml.Spreadsheet.Row();
                    
                    List<DataColumn> columns = new List<DataColumn>();
                    
                    foreach (System.Data.DataColumn column in table.Columns)
                    {
                        columns.Add(column);
                        
                        DocumentFormat.OpenXml.Spreadsheet.Cell cell = new DocumentFormat.OpenXml.Spreadsheet.Cell();
                        cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.String;
                        cell.CellValue = new DocumentFormat.OpenXml.Spreadsheet.CellValue("<b>"+ column.ColumnName + "</b>");                      

                        colRow.AppendChild(cell);                        
                    }

                    sheetData.AppendChild(colRow);
                    string valueN;
                    foreach (System.Data.DataRow dsrow in table.Rows)
                    {
                        
                        DocumentFormat.OpenXml.Spreadsheet.Row newRow = new DocumentFormat.OpenXml.Spreadsheet.Row();
                        foreach (DataColumn col in columns)
                        {
                            DocumentFormat.OpenXml.Spreadsheet.Cell cell = new DocumentFormat.OpenXml.Spreadsheet.Cell();
                            cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.String;

                            if (col.DataType.Equals(typeof(byte[])) == true)
                            {
                                 valueN = ConvertByteArraytoInteger(dsrow[col.ColumnName]).ToString();
                                
                                cell.CellValue = new DocumentFormat.OpenXml.Spreadsheet.CellValue(valueN);
                            }
                            else
                            {
                                cell.CellValue = new DocumentFormat.OpenXml.Spreadsheet.CellValue(dsrow[col].ToString()); //
                            }
                            newRow.AppendChild(cell);
                        }

                        sheetData.AppendChild(newRow);
                    }
               
                 }
            }
        }

        

But now i have requirements in which data to be exported can be up to 10 lakh records with substantial number of columns. So i had to implement OpenXml Sax type approach as DOM approach is bit slow and memory consuming in case of large data.

I couldn't find any helpful link which shows me how to use that approach and convert data table/data set to excel. In most link they are using existing spreadsheet to create new excel. Can anyone provide changes to be made to above code to implement SAX approach or any link regarding the same.

Any help is deeply appreciated
Thanks

Open xml relationship target is NULL when inserting chart

$
0
0

Hi,

I have looked into the specification ISO/IEC 29500-1:2012 and i understand that the attribute Target for the element Relationship can be set to NULL at times(Empty header and footer in the specification).

Now, i have stumbled on Target being NULL also when inserting a diagram into a word document. For example:

<Relationship Id="rId3" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/oleObject"Target="NULL" TargetMode="External" xmlns="http://schemas.openxmlformats.org/package/2006/relationships" />

I'm using Open xml sdk and i'm trying to create a relationship. My question is how i should resolve the target which i think should point to the diagram/chart that i inserted.

Br,

/Peter


Peter

No buttons working when opening generated OpenXML workbook

$
0
0

Hi,

I've looked around for the answer to this, but have been unable to get anything, so probably looking in the wrong places.

I generate OpenXML worksheets as reports, and some may have stylesheets applied to match the source content defined, or contain charts.

Now the problem is that, while I get the XLSX file generated correctly with all content required, when opening the file in Excel, no menus or buttons are clickableat all - they are not disabled, they are just not clickable. This is the case whether or not I apply a style sheet.

using OpenXML SDK 2.5, Excel 2010

thanks

francois

How to set all columns width to autofit (based on content in cell)

$
0
0

Hi,

I have defined columns something like this:

Worksheet worksheet = new Worksheet(); 

Columns xlCols = new Columns(); 
Column xlCol = new Column(); 
xlCol.Width = 20; 
xlCol.BestFit = true; 
xlCol.CustomWidth = true; 
xlCol.Min = 2; 
xlCol.Max = 6; 
xlCols.Append(xlCol); 

xlCol = new Column(); 
xlCol.Width = 30; 
xlCol.BestFit = true; 
xlCol.CustomWidth = true; 
xlCol.Min = 7; 
xlCol.Max = 9; 
xlCols.Append(xlCol); 

worksheet.Append(xlCols); 

Eventhough BestFit = true, still all columns width is 30 only.

and I cannot find anything such as

xlCols.AutoFit(); in openxml sdk

Could someone please help me on this?



Thumbnail.wmf Extraction

$
0
0

I see that documents with Thumbnails have a Thumbnail.wmf image in docProps (see image). How would I use OpenXML to extract and save this image to show a thumbnail on a web page?


Ray Pietrzak

Convert word document to text

$
0
0

I am attempting to convert a word document to text using OpenXml sdk. Are there any examples of how to do this?

I can open the file, and get the body, but there is no formatting.

OpenSettingsos =newOpenSettings();

WordprocessingDocumentdoc =WordprocessingDocument.Open(fileName,false, os);

Bodybody = doc.MainDocumentPart.Document.Body;

text = body.InnerText;


dave

Create openxml spreadsheet to memory stream

$
0
0

I need to create an openxml spreadsheet from a dataset and stream it back to a browser using asp.net (vb.net).

I can't seem to find anyway to create the spreadsheet to a memory stream without first creating the physical file and saving that to a stream (using openxml anyway). Can someone point me in the right direction?

Excel Cell Format Wrap Text

$
0
0

Hello Team,

I have used OpenXml to update a sheet in excel file. I have achieved this by referring the MSDN

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

Now i am updating an excel cell with large text separated by '\n'. I need to set theWrap Text to the cell through OpenXMl C#. With out wrap text the string is appearing in one line which is disappointed.

I have tried to add a style sheet through code, i got exception "only one instance can be allowed"

Please provide a solution to give wrap text to a cell in excel using open xml. My code is similar to the MSDN 


Any help is appritiated

Thanks & Regards,

Programmer Kadapa


Get Excel cell background color

$
0
0

Hello,

I need the get the cell background color in an excel sheet. please help me with some code example.

I have searched on internet but i have found only one help link.

http://stackoverflow.com/questions/10756206/getting-cell-backgroundcolor-in-excel-with-open-xml-2-0

is this is the only way of doing this? or is there any simple way to get the background color.

Please help me with some code example.

Thanks in Advance!!!

how to apply a custom formatting with OpenXML ?

$
0
0

Hello,

After having solved my first issue on openxml tht was due to a bug in the microsoft samples here : https://social.msdn.microsoft.com/Forums/sqlserver/en-US/47e6023f-361d-41e9-9a51-87a41fa7080d/pb-for-writing-data-in-both-z-and-aa-columns?forum=oxmlsdk

I am coming with a new question. I am generating the following stylesheet :

public static Stylesheet GenerateStyleSheet()
        {
            return new Stylesheet(
                new Fonts(
                    new Font(                                                               // Index 0 - The default font.
                        new FontSize() { Val = 11 },
                        new Color() { Rgb = new HexBinaryValue() { Value = "00000000" } },
                        new FontName() { Val = "Calibri" }),
                    new Font(                                                               // Index 1 - The bold font.
                        new Bold(),
                        new FontSize() { Val = 11 },
                        new Color() { Rgb = new HexBinaryValue() { Value = "00000000" } },
                        new FontName() { Val = "Calibri" })
                ),
                new Fills(
                    new Fill(                                                           // Index 0 - The default fill.
                        new PatternFill() { PatternType = PatternValues.None })
                ),
                new Borders(
                    new Border(                                                         // Index 0 - The default border.
                        new LeftBorder(),
                        new RightBorder(),
                        new TopBorder(),
                        new BottomBorder(),
                        new DiagonalBorder())
                ),
                new CellFormats(
                    new CellFormat() { FontId = 0, FillId = 0, BorderId = 0 },                          // Index 0 - The default cell style.
                    new CellFormat() { FontId = 1, FillId = 0, BorderId = 0, ApplyFont = true }       // Index 1 - Bold
                    , new CellFormat() { FontId = 0, FillId = 0, BorderId = 0, ApplyNumberFormat = true }
                )
            ); // return
        }

And when I want to write in bold, I put "cell.StyleIndex = (UInt32Value)1U" and in normal, I put "cell.StyleIndex = (UInt32Value)2U"

This works fine when I write a number via  : string val1="10000.12345"

It doesn't work if I put : double val2 = 10000.12345; val2.ToString() (because here val2.ToString() returns "10000,12345" (so with a comma instead of a dot))

I would like now to format my numbers when we open my Excel file with string.Format("{0:#,0.00}", val1) and that a " "(space) be the thousand separator.

When I look at the proposed code by Open XML SDK 2.5 Productivity Tool when I open an Excel file that contains just one cell with the format that I want, I don't see anything related to the thousand separator nor with having 2 decimals places.

Can you tell me which stylesheet I should create in order to see what I want ?

Thanks for your help.

How can I figure out what is wrong in a file?


Insert Pie Chart to Excel Using OpenXml

$
0
0
I managed to implement the code(I got from MSDN) to create a bar graph in excel, I am however facing challenges in creating a piechart, I had thought that I can manipulate the code a little bit and  produce a pie chart-but I have spent nights and nights still can't find my way to create a pie chart. I need help on this, I would appreciate if you can help me through this.

F.Shumba

how to make a cell usable as a number when we apply a format with thousand separators ?

How to handle SharedStringTable ?

$
0
0

Hello,

I am following the example given by Microsoft here but I get the error "Cannot save DOM tree since this element is not associated with an OpenXmlPart" when it tries to save the stringTable. Do you know what I am doing wrong and how to correct it please? Thank you.

My code is as like this so that you can reproduce the issue (2 files in my project) : ThirdAttemptGenericUtils.cs :

using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace ThirdAttemptGenericInsertWorksheet
{
    public static class ThirdAttemptGenericUtils
    {
        public static bool UpdateValue(SpreadsheetDocument spreadsheetDocument, string sheetName, string addressName, string value, UInt32Value styleIndex, bool isString)
        {
            value = value != null ? value : "";
            // Assume failure.
            bool updated = false;
            WorkbookPart wbPart = spreadsheetDocument.WorkbookPart;
            Sheet sheet = wbPart.Workbook.Descendants<Sheet>().Where((s) => s.Name == sheetName).FirstOrDefault();

            if (sheet != null)
            {

                Worksheet ws = ((WorksheetPart)(wbPart.GetPartById(sheet.Id))).Worksheet;
                Cell cell = InsertCellInWorksheet(ws, addressName);

                if (isString)
                {
                    // Either retrieve the index of an existing string,
                    // or insert the string into the shared string table
                    // and get the index of the new item.
                    int stringIndex = InsertSharedStringItem(wbPart, value);

                    cell.CellValue = new CellValue(stringIndex.ToString());
                    cell.DataType = new EnumValue<CellValues>(CellValues.SharedString);
                }
                else
                {
                    cell.CellValue = new CellValue(value);
                    cell.DataType = new EnumValue<CellValues>(CellValues.Number);
                }

                if (styleIndex > 0)
                    cell.StyleIndex = styleIndex;

                // Save the worksheet.
                ws.Save();
                updated = true;
            }

            return updated;
        }

        public static void InsertWorkSheet(SpreadsheetDocument spreadsheetDocument, string worksheetLabel)
        {
            // Add or Get a WorkbookPart to or from the document.
            WorkbookPart workbookPart;
            if (spreadsheetDocument.WorkbookPart == null)
            {
                workbookPart = spreadsheetDocument.AddWorkbookPart();
                workbookPart.Workbook = new Workbook();
                workbookPart.Workbook.Save();
            }
            else
                workbookPart = spreadsheetDocument.WorkbookPart;

            //Handling Stylesheet
            WorkbookStylesPart workbookStylesPart;
            if (workbookPart.WorkbookStylesPart == null)
                workbookStylesPart = workbookPart.AddNewPart<WorkbookStylesPart>();
            else
                workbookStylesPart = workbookPart.WorkbookStylesPart;
            if (workbookStylesPart.Stylesheet == null)
            {
                workbookStylesPart.Stylesheet = GenerateStyleSheet();
                workbookStylesPart.Stylesheet.Save();
            }

            // Add or Get Sheets to or from the Workbook.
            Sheets sheets;
            if (spreadsheetDocument.WorkbookPart.Workbook.Sheets == null)
                sheets = spreadsheetDocument.WorkbookPart.Workbook.AppendChild<Sheets>(new Sheets());
            else
                sheets = spreadsheetDocument.WorkbookPart.Workbook.GetFirstChild<Sheets>();

            WorksheetPart newWorksheetPart = workbookPart.AddNewPart<WorksheetPart>();
            newWorksheetPart.Worksheet = new Worksheet(new SheetData());
            newWorksheetPart.Worksheet.Save();
            string relationshipId = workbookPart.GetIdOfPart(newWorksheetPart);

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


            // Add the new worksheet and associate it with the workbook.
            Sheet sheet = new Sheet();
            sheet.Id = relationshipId;
            sheet.SheetId = sheetId;
            sheet.Name = worksheetLabel;
            sheets.Append(sheet);

            workbookPart.Workbook.Save();
        }


        // Given a Worksheet and an address (like "AZ254"), either return a cell reference, or
        // create the cell reference and return it.
        public static Cell InsertCellInWorksheet(Worksheet ws, string addressName)
        {
            SheetData sheetData = ws.GetFirstChild<SheetData>();
            Cell cell = null;

            UInt32 rowNumber = GetRowIndex(addressName);
            Row row = GetRow(sheetData, rowNumber);

            // If the cell you need already exists, return it.
            // If there is not a cell with the specified column name, insert one.
            Cell refCell = row.Elements<Cell>().
                Where(c => c.CellReference.Value == addressName).FirstOrDefault();
            if (refCell != null)
            {
                cell = refCell;
            }
            else
            {
                cell = CreateCell(row, addressName);
            }
            return cell;
        }

        public static Cell CreateCell(Row row, String address)
        {
            Cell cellResult;
            Cell refCell = null;

            // Cells must be in sequential order according to CellReference. Determine where to insert the new cell.
            foreach (Cell cell in row.Elements<Cell>())
            {
                if (Regex.Replace(cell.CellReference.Value, @"[\d-]", string.Empty).fromBase26() > Regex.Replace(address, @"[\d-]", string.Empty).fromBase26())
                {
                    refCell = cell;
                    break;
                }
            }

            cellResult = new Cell();
            cellResult.CellReference = address;

            row.InsertBefore(cellResult, refCell);
            return cellResult;
        }

        // Given the main workbook part, and a text value, insert the text into the shared
        // string table. Create the table if necessary. If the value already exists, return
        // its index. If it doesn't exist, insert it and return its new index.
        public static int InsertSharedStringItem(WorkbookPart wbPart, string value)
        {
            value = value != null ? value : "";
            int index = 0;
            bool found = false;
            var stringTablePart = wbPart.GetPartsOfType<SharedStringTablePart>().FirstOrDefault();

            // If the shared string table is missing, something's wrong.
            // Just return the index that you found in the cell.
            // Otherwise, look up the correct text in the table.
            if (stringTablePart == null)
            {
                // Create it.
                stringTablePart = wbPart.AddNewPart<SharedStringTablePart>();
            }

            var stringTable = stringTablePart.SharedStringTable;
            if (stringTable == null)
            {
                stringTable = new SharedStringTable();
            }

            // Iterate through all the items in the SharedStringTable. If the text already exists, return its index.
            foreach (SharedStringItem item in stringTable.Elements<SharedStringItem>())
            {
                if (item.InnerText == value)
                {
                    found = true;
                    break;
                }
                index += 1;
            }

            if (!found)
            {
                stringTable.AppendChild(new SharedStringItem(new Text(value)));
                stringTable.Save();
            }

            return index;
        }


        public static Stylesheet GenerateStyleSheet()
        {
            return new Stylesheet(
                new Fonts(
                    new Font(                                                               // Index 0 - The default font.
                        new FontSize() { Val = 11 },
                        new Color() { Rgb = new HexBinaryValue() { Value = "00000000" } },
                        new FontName() { Val = "Calibri" }),
                    new Font(                                                               // Index 1 - The bold font.
                        new Bold(),
                        new FontSize() { Val = 11 },
                        new Color() { Rgb = new HexBinaryValue() { Value = "00000000" } },
                        new FontName() { Val = "Calibri" })
                ),
                new Fills(
                    new Fill(                                                           // Index 0 - The default fill.
                        new PatternFill() { PatternType = PatternValues.None })
                ),
                new Borders(
                    new Border(                                                         // Index 0 - The default border.
                        new LeftBorder(),
                        new RightBorder(),
                        new TopBorder(),
                        new BottomBorder(),
                        new DiagonalBorder())
                ),
                new CellFormats(
                    new CellFormat() { FontId = 0, FillId = 0, BorderId = 0 },                          // Index 0 - The default cell style.  If a cell does not have a style index applied it will use this style combination instead
                    new CellFormat() { FontId = 1, FillId = 0, BorderId = 0, ApplyFont = true }       // Index 1 - Bold
                    , new CellFormat() { FontId = 0, FillId = 0, BorderId = 0, ApplyNumberFormat = true }
                )
            ); // return
        }

        public static Row GetRow(SheetData wsData, UInt32 rowIndex)
        {
            var row = wsData.Elements<Row>().
            Where(r => r.RowIndex.Value == rowIndex).FirstOrDefault();
            if (row == null)
            {
                row = new Row();
                row.RowIndex = rowIndex;
                wsData.Append(row);
            }
            return row;
        }

        public static UInt32 GetRowIndex(string address)
        {
            string rowPart;
            UInt32 l;
            UInt32 result = 0;

            for (int i = 0; i < address.Length; i++)
            {
                if (UInt32.TryParse(address.Substring(i, 1), out l))
                {
                    rowPart = address.Substring(i, address.Length - i);
                    if (UInt32.TryParse(rowPart, out l))
                    {
                        result = l;
                        break;
                    }
                }
            }
            return result;
        }

        //Hexavigesimal (Excel Column Name to Number) - Bijective
        public static int fromBase26(this string colName)
        {
            colName = colName.ToUpper();
            int decimalValue = 0;
            for (int i = 0; i < colName.Length; i++)
            {
                decimalValue *= 26;
                decimalValue += (colName[i] - 64);
            }
            return decimalValue;
        }

    }
}

and ThirdAttemptGeneric.cs :

using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ThirdAttemptGenericInsertWorksheet
{
    class ThirdAttemptGeneric
    {
        static void Main(string[] args)
        {
            UInt32Value normalFontIndex = (UInt32Value)2U;
            string filename = string.Format("{0}BulkResult_{1}{2:00}{3:00}{4:00}{5:00}{6:00}{7:000}.xlsx", System.IO.Path.GetTempPath(), DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.UtcNow.Day, DateTime.UtcNow.Hour, DateTime.UtcNow.Minute, DateTime.UtcNow.Second, DateTime.UtcNow.Millisecond);

            SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Create(filename, SpreadsheetDocumentType.Workbook);
            string worksheet1 = "WS1";
            ThirdAttemptGenericUtils.InsertWorkSheet(spreadsheetDocument, worksheet1);
            ThirdAttemptGenericUtils.UpdateValue(spreadsheetDocument, worksheet1, "A1", "Val1", normalFontIndex, true);

            spreadsheetDocument.Close();
            System.Diagnostics.Process.Start(filename);
        }
    }
}


Open XML SDK - WinRT (Windows store)

$
0
0
Anybody have any luck using the Open XML SDK in a WinRT/Windows Store app?  I tried adding the V2.5 DocumentFormat.OpenXml.dll to my project but then it complained about needing a reference to WindowsBase.dll to support System.IO.Packaging.Package.  Adding a reference to WindowsBase.dll causes all kinds of other problems.

Insert a Picture into the Picture/Image Content Control using Open XML SDK 2.0

$
0
0

I have created a word template as follows

Here PizzaPicture is a Picture Content Control, PizzaName is a Plain Text Content Control and PizzaDescription is a Rich Text Content Control

 

I am able to assign text to PizzaName and PizzaDescription Easily but not able to even locate the PizzaPicture. Here is my code

 

using (WordprocessingDocument document = WordprocessingDocument.Open(@".\test.docx", true)) {

                MainDocumentPart mainPart = document.MainDocumentPart;
                DocumentFormat.OpenXml.Wordprocessing.Text text = null;
                SdtContentBlock pizzaNameBlock = null;
                SdtContentBlock pizzaDescriptionBlock = null;//SdtContentBlock pizzaPictureBlock = null;  

                List<SdtBlock> sdtList = mainPart.Document.Descendants<SdtBlock>().ToList();foreach (SdtBlock sdt in sdtList)
                {
                    Console.WriteLine(sdt.SdtProperties.GetFirstChild<Tag>().Val.Value);
                }

                SdtBlock s1 = mainPart.Document.Body.Descendants<SdtBlock>().Where(r => r.SdtProperties.GetFirstChild<Tag>().Val == "PizzaName").Single();
                SdtBlock s2 = mainPart.Document.Body.Descendants<SdtBlock>().Where(r => r.SdtProperties.GetFirstChild<Tag>().Val == "PizzaDescription").Single();
                SdtBlock s3 = mainPart.Document.Body.Descendants<SdtBlock>().FirstOrDefault(r =>
                {
                    SdtProperties p = r.Elements<SdtProperties>().FirstOrDefault();if (p != null)
                    {
                        Console.WriteLine("P is not null");// Is it a picture content control?
                        SdtContentPicture pict =
                            p.Elements<SdtContentPicture>().FirstOrDefault();if (pict != null) Console.WriteLine("Pict is not null");// Get the alias.
                        SdtAlias a = p.Elements<SdtAlias>().FirstOrDefault();if (pict != null&& a.Val == "PizzaPicture")returntrue;
                    }returnfalse;
                });if (s3 == null) {
                    Console.Write(" s3 is Null");
                } else {
                    Console.WriteLine("s3 not null");
                }if (s1 != null) {
                    pizzaNameBlock = s1.Descendants<SdtContentBlock>().FirstOrDefault();
                    text = pizzaNameBlock.Descendants<DocumentFormat.OpenXml.Wordprocessing.Text>().FirstOrDefault();// here you can set the current time
                    text.Text = "Peperoni";
                    Console.WriteLine(text.Text);
                }string embed = null;if (s3 != null)
                {
                    Drawing dr = s3.Descendants<Drawing>().FirstOrDefault();if (dr != null)
                    {
                        Blip blip = dr.Descendants<Blip>().FirstOrDefault();if (blip != null)
                            embed = blip.Embed;
                    }
                }if (embed != null)
                {
                    IdPartPair idpp = document.MainDocumentPart.Parts
                        .Where(pa => pa.RelationshipId == embed).FirstOrDefault();if (idpp != null)
                    {
                        ImagePart ip = (ImagePart)idpp.OpenXmlPart;using (FileStream fileStream =
                            File.Open(@"c:\temp\pepperoni.jpg", FileMode.Open))
                            ip.FeedData(fileStream);
                    }
                }if (s2 != null) {
                    pizzaDescriptionBlock = s2.Descendants<SdtContentBlock>().FirstOrDefault();string altChunkId = "AltChunkId12345";
                    AlternativeFormatImportPart chunk = mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.Xhtml, altChunkId);
                    chunk.FeedData(File.Open(@".\html.txt", FileMode.Open));
                    AltChunk altChunk = new AltChunk();
                    altChunk.Id = altChunkId;////Replace content control with altChunk information                
                    OpenXmlElement parent = pizzaDescriptionBlock.Parent;
                    parent.InsertAfter(altChunk, pizzaDescriptionBlock);
                    pizzaDescriptionBlock.Remove();
                }

                mainPart.Document.Save();
                document.Close();
            }


Here the call mainPart.Document.Descendants<SdtBlock>().ToList(); returns me only 2 items PizzaName, PizzaDescription butno PizzaPicture.

 

Secondly the line   SdtContentPicture pict =  p.Elements<SdtContentPicture>().FirstOrDefault();returns NULL. So it seems that there is no element of type SdtContentPicture.

What am I doing wrong? I am pretty sure that I have put PizzaPicture as a Picture content control.

 

My objective is to locate this control in the document and then insert an image into it programmatically.

 

 


MSDNStudent Knows not much!
Viewing all 1288 articles
Browse latest View live


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