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

create a new document from word template with multiple pages

$
0
0

I have a word template with some content controls. 

In the page, I would like to inject new text from a rest service. The rest service returns an array of data, I need to replicate the information in each page (in the new document) based on the MS Word template that I have created.

I found this post here which is great, but I don't know how can I apply the array of data to multiple pages from the same template. The content controls are located in the second page of the template and that page needs to be replicated in the multiple pages in the new document.

So, how can I create multiple pages from the same template in a new document?

Thank you.



create a new document with multiple pages from word template

$
0
0

I have a word template with some content controls. 

In the page, I would like to inject new text from a rest service. The rest service returns an array of data, I need to replicate the information in each page (in the new document) based on the MS Word template that I have created.

I found this post here which is great, but I don't know how can I apply the array of data to multiple pages from the same template. The content controls are located in the second page of the template and that page needs to be replicated in the multiple pages in the new document.

So, how can I create multiple pages from the same template in a new document?

Thank you.



Merging updated templates in memory and creating a single document

$
0
0

I have split my template into two documents. I woud like to load the first document and add it into the memory, then load the second document in memory and then make a few modifications to the content controls and then add it to the previous memory buffer, then modify the second document again with some new data and add that again to the memory buffer till the last item in the list of data.

then I would like to save this document.

I wold like to do this using open xml. Any help in the right direction? Thank you.

the code that I have now is like this. It is only the calling code. I can't place all the code in here as it is long

            

        public static DocGenSample GenerateDocumentUsingDocGenerator(string jsondata)
        {
            string templateFile = "DG-NS-Template-Body.docx";
            string newDocFile = "NewDocB.docx";
            string docPropName = "Document";
            string docVersion = "1.0";
            byte[] result = null;
            var reportsData = GetDataContext(jsondata);
            DocGenSample sampleRefreshableDocumentGenerator = null;
            foreach (var rep in reportsData)
            {
                DocumentGenerationInfo generationInfo = GetDocumentGenerationInfo(docPropName, docVersion, rep, templateFile, false);
                sampleRefreshableDocumentGenerator = new DocGenSample(generationInfo);
                result = sampleRefreshableDocumentGenerator.GenerateDocument();
            }

            WriteOutputToFile(newDocFile, templateFile, result);

            return sampleRefreshableDocumentGenerator;
        }

for every loop, I would like to add the bytes to the previous bytes and that is represented by the result variable. How can I modify this code so I can join multiple bytes of array into one byte array and write it to file. At the moment I am using File.WriteAllBytes(Path.Combine("Docs", fileName), fileContents);

how to modify content in filestream while using open xml?

$
0
0

In the code below, I am merging some files together and saving them in the test.docx file. However, before I merg each file, I would like to first replace the text of some content controls which are used as place holders. Can someone show me how to do that?

suppose I have one content control in template2 and it is called placeholder1. How can I add text to this placeholder while usig the filestream? 

string fileName = Path.Combine(@"Docs\templates", "test.docx");
            for (int i = 1; i < 3; i++)
            {
                string filePath = Path.Combine(@"Docs\templates", "report-Part" + i + ".docx");

                //using (MemoryStream ms = new MemoryStream())
                //{
                //ms.Write(templateFile, 0, templateFile.Length);
                using (WordprocessingDocument myDoc = WordprocessingDocument.Open(fileName, true))
                {
                    MainDocumentPart mainPart = myDoc.MainDocumentPart;
                    string altChunkId = "AltChunkId" + Guid.NewGuid();
                    AlternativeFormatImportPart chunk = mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.WordprocessingML, altChunkId);
                    using (FileStream fileStream = File.Open(filePath, FileMode.Open))
                    {
                        chunk.FeedData(fileStream);
                    }
                    //chunk.FeedData(ms);
                    AltChunk altChunk = new AltChunk();
                    altChunk.Id = altChunkId;

                    Paragraph paragraph2 = new Paragraph() { RsidParagraphAddition = "00BE27E7", RsidRunAdditionDefault = "00BE27E7" };

                    Run run2 = new Run();
                    Break break1 = new Break() { Type = BreakValues.Page };

                    run2.Append(break1);
                    paragraph2.Append(run2);
                    mainPart.Document.Body.Append(paragraph2);
                    var lastParagraph = mainPart.Document.Body.Elements<Paragraph>().Last();
                    mainPart.Document.Body.InsertAfter(altChunk, lastParagraph);
                    mainPart.Document.Save();
                    myDoc.Close();
                }
                //ms.Position = 0;
                ////ms.ToArray();
                //output = new byte[ms.ToArray().Length];
                //ms.Read(output, 0, output.Length);
                //}

               

How to append bytes to memorystream after modifying the word templates?

$
0
0

In the code below I am opening a word document which I use as a template. It contains two pages. The first contains a table of content and some other text, the second one contains some content controls which I use them as place holders.

The code below, loads the document in memory, replaces the content controls with data and then in another method I save document to disk. 

So far it is good, but now I need to replicate the content controls found in the second page of the template and add them in the new document, continuously till the array of data is out.

the image below portrays the template. 

          byte[] output = null;

            using (MemoryStream ms = new MemoryStream())
            {
                ms.Write(this.generationInfo.TemplateData, 0, this.generationInfo.TemplateData.Length);

                using (WordprocessingDocument wordDocument = WordprocessingDocument.Open(ms, true))
                {
                    wordDocument.ChangeDocumentType(WordprocessingDocumentType.Document);
                    MainDocumentPart mainDocumentPart = wordDocument.MainDocumentPart;
                    Document document = mainDocumentPart.Document;

                    if (this.generationInfo.Metadata != null)
                    {
                        SetDocumentProperties(mainDocumentPart, this.generationInfo.Metadata);
                    }

                    if (this.generationInfo.IsDataBoundControls)
                    {
                        SaveDataToDataBoundControlsDataStore(mainDocumentPart);
                    }

                    foreach (HeaderPart part in mainDocumentPart.HeaderParts)
                    {
                        this.SetContentInPlaceholders(new OpenXmlElementDataContext() { Element = part.Header, DataContext = this.generationInfo.DataContext });
                        part.Header.Save();
                    }

                    foreach (FooterPart part in mainDocumentPart.FooterParts)
                    {
                        this.SetContentInPlaceholders(new OpenXmlElementDataContext() { Element = part.Footer, DataContext = this.generationInfo.DataContext });
                        part.Footer.Save();
                    }

                    this.SetContentInPlaceholders(new OpenXmlElementDataContext() { Element = document, DataContext = this.generationInfo.DataContext });

                    this.openXmlHelper.EnsureUniqueContentControlIdsForMainDocumentPart(mainDocumentPart);

                    document.Save();
                }

                ms.Position = 0;
                output = new byte[ms.Length];
                ms.Read(output, 0, output.Length);
            }

            return output;

OpenXML generated file wont open in MS Spreadsheet Compare tool and Excel "Open and Repair" also reports a problem

$
0
0

We are trying to build new process to auto generate Excel files using OpenXML (2.8.1.0). The very basic XLSX file will open in Excel, but when I try to use the MS tool Spreadsheet Compare tool, it can't open the file. The error we are getting is

"Error opening workbook. Attempted to read past the end of the stream"

If I open the OpenXML generated file in Excel and save it first, the file can now be opened by the Spreadsheet Comparison tool. Excel is fixing/adding something to the file that is missing from OpenXML generated file.

I used this MSDN sample code as a very basic starting point to help demonstrate the problem
https://msdn.microsoft.com/en-us/library/office/ff478153.aspx

The goal is to use the Spreadsheet comparison tool to make sure what we are generating is matching the old process that created the same file.

I ran the file the "Open and Repair" in the Excel file open dialog, and it gives me this report on the original file generated from the above sample.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?><recoveryLog xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><logFileName>error260080_01.xml</logFileName><summary>Errors were detected in file 'C:\TEMP\testing.xlsx'</summary><additionalInfo><info>Excel completed file level validation and repair. Some parts of this workbook may have been repaired or discarded.</info></additionalInfo></recoveryLog>

Thank you 

How do I add UID to xl/table file using OpenXML?

$
0
0
I output an xlsx with a table defined using the following code:

        protected void ExcelOut(string FName, DataTable table)
        {
            // Get table schema to ensure proper column formats
            DataTable dtSchema = CommonFunctions.getSchema("WorkloadPerformanceResults_PV", UpdateEnvironment);

            MemoryStream ms = new MemoryStream();

            // Create a spreadsheet document by supplying the memorystream.
            // By default, AutoSave = true, Editable = true, and Type = xlsx.
            SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Create(ms, SpreadsheetDocumentType.Workbook);

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

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

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

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

            // Get the sheetData cell table.
            SheetData sheetData = worksheetPart.Worksheet.GetFirstChild<SheetData>();

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

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

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

            sheetData.AppendChild(headerRow);
            int NumRows = table.Rows.Count;
            foreach (DataRow dsrow in table.Rows)
            {
                DocumentFormat.OpenXml.Spreadsheet.Row newRow = new DocumentFormat.OpenXml.Spreadsheet.Row();
                foreach (String col in columns)
                {
                    string dataType = "";

                    foreach (DataRow SchemaDR in dtSchema.Rows)
                    {
                        string dcName = SchemaDR["COLUMN_NAME"].ToString().ToUpper();
                        string dsrowName = col.ToString().ToUpper();
                        if (dcName == dsrowName)
                        {
                            dataType = SchemaDR["DATA_TYPE"].ToString();
                        }
                    }
                    DocumentFormat.OpenXml.Spreadsheet.Cell cell = new DocumentFormat.OpenXml.Spreadsheet.Cell();
                    // Need to get the data type of the col
                    switch (dataType)
                    {
                        case "bit":
                            cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.Boolean;
                            break;
                        case "date":
                        case "datetime":
                        case "datetime2":
                        case "smalldatetime":
                        case "DateTime":
                            cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.Date;
                            break;
                        case "bigint":
                        case "int":
                        case "decimal":
                        case "float":
                        case "money":
                        case "numeric":
                        case "smallint":
                        case "smallmoney":
                        case "tinyint":
                        case "UInt32":
                        case "UInt64":
                            cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.Number;
                            break;
                        case "nchar":
                        case "nvarchar":
                        case "text":
                            cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.String;
                            break;
                        default:
                            cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.String;
                            break;
                    }

                    cell.CellValue = new DocumentFormat.OpenXml.Spreadsheet.CellValue(dsrow[col].ToString()); //
                    newRow.AppendChild(cell);
                }

                sheetData.AppendChild(newRow);
            }
            // Add table to sheet
            TableDefinitionPart tdp = worksheetPart.AddNewPart<TableDefinitionPart>("rId1");

            tdp.Table = GenerateTableDefinitionPart1Content(tdp, NumRows);
            
            TableParts tableparts1 = new TableParts() { Count = 1 };
            //TableParts tableparts1 = new TableParts();
            TablePart tablepart1 = new TablePart() { Id = "rId1" };
            tableparts1.Append(tablepart1);
            worksheetPart.Worksheet.Append(tableparts1);

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

            // push memorystream to response
            Response.Clear();
            Response.ContentType = "Application/msexcel";
            Response.AddHeader("Content-Disposition", "attachment; filename=" + FName + ".xlsx");
            Response.BinaryWrite(ms.ToArray());
            // myMemoryStream.WriteTo(Response.OutputStream); //works too
            Response.Flush();
            Response.Close();
            Response.End();
        }

        private DocumentFormat.OpenXml.Spreadsheet.Table GenerateTableDefinitionPart1Content(TableDefinitionPart tableDefinitionPart1, int NumRows)
        {
            //'Table' is an ambiguous reference between 'DocumentFormat.OpenXml.Spreadsheet.Table' and 'System.Web.UI.WebControls.Table'
            DocumentFormat.OpenXml.Spreadsheet.Table table1 = new DocumentFormat.OpenXml.Spreadsheet.Table() { Id = (UInt32Value)1U, Name = "Table1", DisplayName = "Table1", Reference = "A1:M27", TotalsRowShown = false };
            AutoFilter autoFilter1 = new AutoFilter() { Reference = "A1:M" + NumRows.ToString() };

            TableColumns tableColumns1 = new TableColumns() { Count = 13 };
            TableColumn tableColumn1 = new TableColumn() { Id = (UInt32Value)1U, Name = "PlatformName" };
            TableColumn tableColumn2 = new TableColumn() { Id = (UInt32Value)2U, Name = "domain" };
            TableColumn tableColumn3 = new TableColumn() { Id = (UInt32Value)3U, Name = "industryVertical" };
            TableColumn tableColumn4 = new TableColumn() { Id = (UInt32Value)4U, Name = "engineer" };
            TableColumn tableColumn5 = new TableColumn() { Id = (UInt32Value)5U, Name = "appName" };
            TableColumn tableColumn6 = new TableColumn() { Id = (UInt32Value)6U, Name = "appVersion" };
            TableColumn tableColumn7 = new TableColumn() { Id = (UInt32Value)7U, Name = "workloadName" };
            TableColumn tableColumn8 = new TableColumn() { Id = (UInt32Value)8U, Name = "units" };
            TableColumn tableColumn9 = new TableColumn() { Id = (UInt32Value)9U, Name = "isBetter" };
            TableColumn tableColumn10 = new TableColumn() { Id = (UInt32Value)10U, Name = "nodes" };
            TableColumn tableColumn11 = new TableColumn() { Id = (UInt32Value)11U, Name = "time_Stamp" };
            TableColumn tableColumn12 = new TableColumn() { Id = (UInt32Value)12U, Name = "workloadResult" };
            TableColumn tableColumn13 = new TableColumn() { Id = (UInt32Value)13U, Name = "buildNotes" };
            tableColumns1.Append(tableColumn1);
            tableColumns1.Append(tableColumn2);
            tableColumns1.Append(tableColumn3);
            tableColumns1.Append(tableColumn4);
            tableColumns1.Append(tableColumn5);
            tableColumns1.Append(tableColumn6);
            tableColumns1.Append(tableColumn7);
            tableColumns1.Append(tableColumn8);
            tableColumns1.Append(tableColumn9);
            tableColumns1.Append(tableColumn10);
            tableColumns1.Append(tableColumn11);
            tableColumns1.Append(tableColumn12);
            tableColumns1.Append(tableColumn13);
            TableStyleInfo tableStyleInfo1 = new TableStyleInfo() { Name = "TableStyleLight17", ShowFirstColumn = false, ShowLastColumn = false, ShowRowStripes = true, ShowColumnStripes = false };

            table1.Append(autoFilter1);
            table1.Append(tableColumns1);
            table1.Append(tableStyleInfo1);

            //tableDefinitionPart1.Table = table1;
            return table1;
        }

(NOTE: I know, the code can be shorter by looping.  This is just to make it functional before optimizing)

It generates the following xl/table content:

<?xml version="1.0" encoding="utf-8"?><x:table id="1" name="Table1" displayName="Table1" ref="A1:M27" totalsRowShown="0" xmlns:x="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><x:autoFilter ref="A1:M26" /><x:tableColumns count="13"><x:tableColumn id="1" name="PlatformName" /><x:tableColumn id="2" name="domain" /><x:tableColumn id="3" name="industryVertical" /><x:tableColumn id="4" name="engineer" /><x:tableColumn id="5" name="appName" /><x:tableColumn id="6" name="appVersion" /><x:tableColumn id="7" name="workloadName" /><x:tableColumn id="8" name="units" /><x:tableColumn id="9" name="isBetter" /><x:tableColumn id="10" name="nodes" /><x:tableColumn id="11" name="time_Stamp" /><x:tableColumn id="12" name="workloadResult" /><x:tableColumn id="13" name="buildNotes" /></x:tableColumns><x:tableStyleInfo name="TableStyleLight17" showFirstColumn="0" showLastColumn="0" showRowStripes="1" showColumnStripes="0" /></x:table>

You will notice it does not have any xr3:uid etc

When I try reading the file using "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + gFName + ";Extended Properties=Excel 12.0" I get the following error:  External table is not in the expected format.

I open the file in excel and save it back and the xl/table looks like this:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<table xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="xr xr3" xmlns:xr="http://schemas.microsoft.com/office/spreadsheetml/2014/revision" xmlns:xr3="http://schemas.microsoft.com/office/spreadsheetml/2016/revision3" id="1" xr:uid="{00000000-000C-0000-FFFF-FFFF00000000}" name="Table1" displayName="Table1" ref="A1:M27" totalsRowShown="0"><autoFilter ref="A1:M27" xr:uid="{00000000-0009-0000-0100-000001000000}"/><tableColumns count="13"><tableColumn id="1" xr3:uid="{00000000-0010-0000-0000-000001000000}" name="PlatformName"/><tableColumn id="2" xr3:uid="{00000000-0010-0000-0000-000002000000}" name="domain"/><tableColumn id="3" xr3:uid="{00000000-0010-0000-0000-000003000000}" name="industryVertical"/><tableColumn id="4" xr3:uid="{00000000-0010-0000-0000-000004000000}" name="engineer"/><tableColumn id="5" xr3:uid="{00000000-0010-0000-0000-000005000000}" name="appName"/><tableColumn id="6" xr3:uid="{00000000-0010-0000-0000-000006000000}" name="appVersion"/><tableColumn id="7" xr3:uid="{00000000-0010-0000-0000-000007000000}" name="workloadName"/><tableColumn id="8" xr3:uid="{00000000-0010-0000-0000-000008000000}" name="units"/><tableColumn id="9" xr3:uid="{00000000-0010-0000-0000-000009000000}" name="isBetter"/><tableColumn id="10" xr3:uid="{00000000-0010-0000-0000-00000A000000}" name="nodes"/><tableColumn id="11" xr3:uid="{00000000-0010-0000-0000-00000B000000}" name="time_Stamp"/><tableColumn id="12" xr3:uid="{00000000-0010-0000-0000-00000C000000}" name="workloadResult"/><tableColumn id="13" xr3:uid="{00000000-0010-0000-0000-00000D000000}" name="buildNotes"/></tableColumns><tableStyleInfo name="TableStyleLight17" showFirstColumn="0" showLastColumn="0" showRowStripes="1" showColumnStripes="0"/></table>

with all the unique IDs.

Using this file works.

How can I get this to happen on the initial output so the manual process of opening and re-saving doesn't have to happen?


Differences between section break Next Page and Continuous

$
0
0

Hello when processing documents i am trying to understand how to tell the difference between section breaks that are continuous and section breaks that are "Next Page"

This xml for sectPr renders as "Continuous" in word 16

     <w:sectPr w:rsidR="002B0128" w:rsidRPr="002106CC" w:rsidSect="00FA008C">
       
<w:headerReference w:type="first" r:id="rId16"/>
       
<w:footerReference w:type="first" r:id="rId17"/>
       
<w:pgSz w:w="12240" w:h="15840" w:code="1"/>
       
<w:pgMar w:top="1152" w:right="1152" w:bottom="1152" w:left="1152" w:header="720"
            w:footer="505" w:gutter="0"/>
       
<w:pgNumType w:start="1"/>
       
<w:cols w:space="720"/>
       
<w:titlePg/>
       
<w:docGrid w:linePitch="272"/>
   
</w:sectPr>

This xml renders as "Next Page"    

<w:sectPr w:rsidR="002B0128" w:rsidRPr="004C2324" w:rsidSect="00A836DF">

        <w:footerReference w:type="even" r:id="rId12"/>
       
<w:footerReference w:type="default" r:id="rId13"/>
       
<w:headerReference w:type="first" r:id="rId14"/>
       
<w:footerReference w:type="first" r:id="rId15"/>
       
<w:pgSz w:w="12240" w:h="15840" w:code="1"/>
       
<w:pgMar w:top="1080" w:right="1152" w:bottom="994" w:left="1152" w:header="446"
            w:footer="634" w:gutter="0"/>
       
<w:pgNumType w:start="1"/>
       
<w:cols w:space="720"/>
       
<w:titlePg/>
   
</w:sectPr>

Word does not seem to consistently use the 

 <w:type w:val="continuous"/>

child element.   I have even seen section breaks with type=continuous rendered as "Next page"

Is there some linked data element that determines the break type?

 I found a blog post that indicated  the "type" of a section break is actually controlled by the value of the following section break element.   
https://blogs.msmvps.com/wordmeister/2013/07/21/open-xml-sdk-cont-section-breaks/

tests on editing the xml show this to be true.

can anyone explain the thinking behind this? 


OpenXML in UWP (Revised)

$
0
0

Hi! I have created an excel application that can read and write xlsx file using Unity (Client) , Visual Studio (DLL) and openxml (library). I was able to make the program run. But whenever I tried to create a new excel file, Add image etc. invoking these methods: AddImagePart(), AddNewPart(),  AddWorkbookPark() etc. makes me encounter a runtime error having a conflict with System.IO.Packaging.In order to make my program run, I simply disable the functions that will invoke creating new xlsx file, add new image etc.

Moreover, when I was able to build my app, I was able to read and write the given xlsx file. However, When I tried to build in UWP environment. I encounter two errors: 1. Unable to load advapi32.dll and 2. the reading and writing of xlsx function seems not to work in UWP environment.

Here are my dev environment details:

1. Unity 2018.3.10f1

2. Visual Studio 2017 (Latest version update, UWP and Unity Customize install)

3. Openxml 2.5.1

Please advice how to proceed. I tried to google for Openxml support in UWP but no good reference appears.


How to hide an Excel Sheet?

$
0
0

Hi,

as I said, I want to hide an Excel-Sheet. I tried this solution:

static void Main(string[] args)
{
  byte[] byteArray = File.ReadAllBytes("D:\\rptTemplate.xlsx");

  using (MemoryStream mem = new MemoryStream())
  {
    mem.Write(byteArray, 0, (int)byteArray.Length);

    using (SpreadsheetDocument rptTemplate = SpreadsheetDocument.Open(mem, true))
    {
      foreach (OpenXmlElement oxe in (rptTemplate.WorkbookPart.Workbook.Sheets).ChildElements)
      {
        if(((DocumentFormat.OpenXml.Spreadsheet.Sheet)(oxe)).Name == "ABC")
        {
          ((DocumentFormat.OpenXml.Spreadsheet.Sheet)(oxe)).State = SheetStateValues.Hidden;

           WorkbookView wv = rptTemplate.WorkbookPart.Workbook.BookViews.ChildElements.First<WorkbookView>();

           if (wv != null)
           {
             wv.ActiveTab = GetIndexOfFirstVisibleSheet(rptTemplate.WorkbookPart.Workbook.Sheets);
           }                       
         }
      }
      rptTemplate.WorkbookPart.Workbook.Save();
    }
  }
}

private static uint GetIndexOfFirstVisibleSheet(Sheets sheets)
{
  uint index = 0;
  foreach (Sheet currentSheet in sheets.Descendants<Sheet>())
  {
    if (currentSheet.State == null || currentSheet.State.Value == SheetStateValues.Visible)
    {
      return index;
    }
    index++;
  }
  throw new Exception("No visible sheet found.");
}

 but I get an NullReferenceException in line 

WorkbookView wv = spreadsheetDocument.WorkbookPart.Workbook.BookViews.ChildElements.First<WorkbookView>();

I tried to write this before:

BookViews bV = new BookViews();
WorkbookView wV = new WorkbookView();
bV.Append(wV);
workbookpart.Workbook.Append(bV);

but it didn't help.

Do anyone know what I'm missing here?

Open XML Spreadsheet style error

$
0
0

I've used the Open XML Format SDK 2.0 to create a simple excel document. Opening the document in Excel first requires Excel to open it. I've narrowed this down to the CellFormats within the Stylesheet. The contents of which are below:

<x:styleSheetxmlns:x="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
 
<x:numFmtscount="4">
   
<x:numFmtnumFmtId="170"formatCode="_-[$GBP]\ * #,##0.00_-;\-[$GBP]\ * #,##0.00_-;_-[$GBP]\ * &quot;-&quot;??_-;_-@_-"/>
   
<x:numFmtnumFmtId="171"formatCode="_-[$EUR]\ * #,##0.00_-;\-[$EUR]\ * #,##0.00_-;_-[$EUR]\ * &quot;-&quot;??_-;_-@_-"/>
   
<x:numFmtnumFmtId="172"formatCode="_-[$SEK]\ * #,##0.00_-;\-[$SEK]\ * #,##0.00_-;_-[$SEK]\ * &quot;-&quot;??_-;_-@_-"/>
   
<x:numFmtnumFmtId="173"formatCode="_-[$NOK]\ * #,##0.00_-;\-[$NOK]\ * #,##0.00_-;_-[$NOK]\ * &quot;-&quot;??_-;_-@_-"/>
 
</x:numFmts>
 
<x:cellXfscount="5">
   
<x:xf/>
   
<x:xfnumFmtId="170"applyNumberFormat="1"/>
   
<x:xfnumFmtId="171"applyNumberFormat="1"/>
   
<x:xfnumFmtId="172"applyNumberFormat="1"/>
   
<x:xfnumFmtId="173"applyNumberFormat="1"/>
 
</x:cellXfs>
</x:styleSheet>

Once Excel has repaired the file it looks like I expect it. However in order to make it look like expected I had to add the empty cell format as the first child. If one of the proper styles were used as the first child, once Excel had repaired the file that style would have been removed.

Any pointers in the right direction would be greatly appreciated.

how to clone a placeholder and its children using open xml?

$
0
0

I have a placeholder in a document. It contains other content place holders and paragraphs.

The intention is to clone this parent placeholder which is called placeholderA, load it in memory, modify the values inside each content control and then save it to a new file.

Anyone can help, please?

Thank you.

update word Customxml part using of OpenXml API, but can't update “document.xml” in Main Document

$
0
0

we update custom xml part using C# code. we are successfully update document in widows. but can we open this document in Linux environment, it could not be changed value.

how can we achieve change of custom xml part in windows as well as Document.xml in word Folder?

How to remove a Column? How about a Row?

$
0
0

How do we programmatically remove a Column in the same fashion as Excel would?

While we are in the topic: How to remove a Row?

TIA

How to convert Xml Spreadsheet 2003 (openxml) to Excel (xls)

$
0
0

Can somebody help me on how to convert my xml spreadsheet 2003 to Excel? I have a page which uses openxml template but the problem is after i rename it to xls extension. this error prompts up.

"The file you are trying to open is in different format that specified by the file extension. Verify that the file is not corrupted and is from a trusted source before opening the file. Do you want to open the file now?

Whats great is that excel can actually convert that xml to excel. maybe i can do the same programmatically. Btw im using asp.net c#. Pls help.

Thanks



How to use AddDigitalSignatureOriginPart (DocumentFormat.OpenXml library)to secure an Excel file?

$
0
0
Need to create a digital signed excel file and then validate the signature when uploaded in C#.

How to embed fonts in presentation using documenformat.openxml c#

$
0
0


I want to embed fonts using documentformat.openxml c# in my presentation(.pptx) but i dont know how to embed.

need help.

Your assistance in this matter would be greatly appreciated.

Thansk & Regards

kamaldeep

OPEN-XML_SDK - Features & Support

$
0
0

Hi

We are evaluating OpenXMLSDK in order to consume as part of our application. Functionally we want to read and write to excel without any dependency on Microsoft Office.

Can you please clarify on the below, so that we can make a decision:

1. DoesOpenXMLSDK support reading/writing in below formats?

XLSX, XLSM, XLTM

2. CanOpenXMLSDK be consumed in either ASP .Net Web Application or ASP .Net Core application?

3. Can this be hosted in cloud (AWS or Azure)?

4. Can you share some references to implementation guide or samples?

5. How about Technical support? Can you please elaborate on this?

How to embed external fonts in presentation with refrence in fonts folder using documenformat.openxml c#

$
0
0

I want to embed external fonts(also create file in fonts folder and create refrence in .rels) using documentformat.openxml c# in my presentation(.pptx) but i dont know how to embed.

need help.

Your assistance in this matter would be greatly appreciated.

Thansk & Regards

kamaldeep

pb for writing data in both Z and AA columns

$
0
0

Hello,

I manage to generate an Excel file with OpenXml but I have a blocking issue in one case.
Indeed, I can write data either : only between columns A and Z or between AA and above.
If I create a very simple sheet with a value in Z1 and a value in AA1, then my Excel file refuses to open and I have the error like there is unreadable content.

But, when I look at the content of the 2 generated files (one that works, the other not), I don't see any structure difference so I am lost...
For information, in order to look into details the content of my xlsx file, I move the extension from xlsx to zip, unzip the file, and I then have access to all the architecture of xml files.

So any idea why and how to workaround please?

Viewing all 1288 articles
Browse latest View live


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