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

Read Excel 2007 file with Open XML - Identify blank cell

$
0
0

Hi

I am working on a .NET 4.0 console application. I am trying to read the data from MS excel 2007 document. (file format in Xlsx)

I use the below code to load the data into datatable. It works fine if all the cells have values. But it does not work when one of the column has blank values.

Data gets shifted to left in the datatable. I will want to fill blank value for the column "Code" in the datatable.

  Data in TestFile.xlsx
FULL NamePanIDPeriodYearCodeType
Name112013012013
1
Name222013022014
2
Name332013032015
3
Name442013042016
4

WindowsBase version 4.0 and DocumentFormat.OpenXML dll reference added

using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml.Packaging;

public void Read2007Xlsx() { try { DataTable dt = new DataTable(); using (SpreadsheetDocument spreadSheetDocument = SpreadsheetDocument.Open(@"D:\2007\Testfile.xlsx", false)) { WorkbookPart workbookPart = spreadSheetDocument.WorkbookPart; IEnumerable<Sheet> sheets = spreadSheetDocument.WorkbookPart.Workbook.GetFirstChild<Sheets>().Elements<Sheet>(); string relationshipId = sheets.First().Id.Value; WorksheetPart worksheetPart = (WorksheetPart)spreadSheetDocument.WorkbookPart.GetPartById(relationshipId); Worksheet workSheet = worksheetPart.Worksheet; SheetData sheetData = workSheet.GetFirstChild<SheetData>(); IEnumerable<Row> rows = sheetData.Descendants<Row>(); foreach (Cell cell in rows.ElementAt(0)) { dt.Columns.Add(GetCellValue(spreadSheetDocument, cell)); } foreach (Row row in rows) //this will also include your header row... { DataRow tempRow = dt.NewRow(); for (int i = 0; i < row.Descendants<Cell>().Count(); i++) { // tempRow[i] = GetCellValue(spreadSheetDocument, row.Descendants<Cell>().ElementAt(i-1)); tempRow[i] = GetCellValue(spreadSheetDocument, row.Descendants<Cell>().ElementAt(i)); } dt.Rows.Add(tempRow); } } dt.Rows.RemoveAt(0); //...so i'm taking it out here. } catch (Exception ex) { } } public static string GetCellValue(SpreadsheetDocument document, Cell cell) { SharedStringTablePart stringTablePart = document.WorkbookPart.SharedStringTablePart; if (cell.CellValue ==null) { return ""; } string value = cell.CellValue.InnerXml; if (cell.DataType != null && cell.DataType.Value == CellValues.SharedString) { return stringTablePart.SharedStringTable.ChildElements[Int32.Parse(value)].InnerText; } else { return value; } }


How to identify if a cell has blank value while reading Xlsx file using Open XML?

How to convert data in Xlsx file into dataset that has blank values using Open XML?

Thanks
Ashok


How to Wrap the Japanese Text in the WordML?

$
0
0

Hi,

I am having a requirement  where I need to display the Japanese Text in WordML. I am able to display the Japanese text using the wordml and opening the document in microsoft word 2013  but the text is not wrapping to next lines as the Japanese text is long in length .

Can anyone suggest the solution for wrapping the Japanese text in WordML.

Thanks in Advance!!!

Thanks.


Newline and spaces are disappeared when open OpenXML generated xlsx file with Excel 2013.

$
0
0
Hi. I generated some xlsx file using OpenXML library, it has some text data with newline and spaces in both after and before texts. Some text has newline in their body. When I read xlsx file with OpenXML library, it's spaces and newline was remained. But if I open xlsx file with Excel 2013, all of spaces and newline has disappeared. After saving in Excel 2013, and read using OpenXML, all text are trimmed in sharedstringtable. 

How to keep newline and spaces in text data with OpenXML excel document, when I open Excel 2013?

Wrong replacement in content controls

$
0
0

Hi Experts,

i have some Word-Documents with Plain-Text Content-Controls. Each one of them has a unique TAG to identify them later by code. In that code part i iterate over all Content Controls to see if the TAG matches my requirements. If so, some Text will be set. This is working fine but for one user some controls having the text value of another control in that document. e.g. The Control 'Worker' has the value of Control 'Deliverydate'. This happens ONLY to one specific user. The code component is having a verbose logger and i can clearly see that the correct values will be written to the controls.

So i think, there is something with the Client. Does anybody may run into the same issue?

Thanks, Ronny

Adding date in the OpenXML Powerpoint

$
0
0

Hi there, I hope your appreciated help.

First of all I must say that I am a newbie when it comes to net language.

This is my problem.

With OpenXml generate powerpoint presentation but I can not adding `date in the for each individual slide.

Can you help me? thank you in advance.
Your help would be very appreciated

<%@ Page Title="Home page" Language="C#" AutoEventWireup="true" %><%@ Import Namespace="DocumentFormat.OpenXml" %><%@ Import Namespace="DocumentFormat.OpenXml.Presentation" %><%@ Import Namespace="DocumentFormat.OpenXml.Packaging" %><%@ Import Namespace="DocumentFormat.OpenXml.Drawing" %>


    public static void CreatePresentation(string OutputFile)
       {
            PresentationDocument presentationDoc = PresentationDocument
                .Create(OutputFile, PresentationDocumentType.Presentation);
            PresentationPart presentationPart = presentationDoc
               .AddPresentationPart();
            
            presentationPart.Presentation = new Presentation();
            CreatePresentationParts(presentationPart);

            presentationDoc.Close();

        }


   public static void PPTReplaceImageOnSlide(string fileName, string slideTitle, string imagePath)
   {
       const string presentationmlNamespace = "http://schemas.openxmlformats.org/presentationml/2006/main";
       const string drawingmlNamespace = "http://schemas.openxmlformats.org/drawingml/2006/main";
       const string relationshipNamespace = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";

...

}

...
       
       Chart1.DataSource = objCmd.ExecuteReader();
       string OutputFile = @"D:\Inetpub\wwwroot\public\safety.pptx";
       this.Chart1.SaveImage(ChartPNG, ChartImageFormat.Png);
       PPTReplaceImageOnSlide(string OutputFile, "Safety", ChartPNG);

Open XML SDK 2.0 xlsx cell hyperlink works in Excel 2010 but in Excel 2007 there is an error

$
0
0

Hello,

I have created myself with the Open XML SDK v2.0.5022.0 one xlsx Excel document that contains links to image files. Xlsx document that I can open in Excel 2010 with no problems and the links work wonderfully, as it should be.

I open the document in Excel 2007, I get the error:

"From Excel unreadable content in DateiXY.xlsx was a template. Want to restore the contents of the workbook?"

Then comes the message:

log file:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?><recoveryLog xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><logFileName>error045280_01.xml</logFileName><summary>Fehler in Datei 'E:\Series.xlsx'</summary><additionalInfo><info>Excel hat die Überprüfung und Reparatur auf Dateiebene abgeschlossen. Einige Teile dieser Arbeitsmappe wurden repariert oder verworfen.</info></additionalInfo><repairedParts summary="Die folgenden Reparaturen wurden durchgeführt:_x000d__x000a__x000d__x000a_"><repairedPart>Reparierter Teil: Teil /xl/worksheets/sheet.xml.</repairedPart></repairedParts><removedFeatures summary="Folgende Features wurden entfernt:"><removedFeature>Entferntes Feature: Hyperlinks von /xl/worksheets/sheet.xml-Part</removedFeature></removedFeatures></recoveryLog>

C# Code:

// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Class1.cs" company="Private">
//   ©  2012 Private
// </copyright>
// <summary>
//   Class to help to build an Xlsx File
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace DatenExportModul.Excel
{
    using System;
    using System.IO;
    using System.Linq;

    using DocumentFormat.OpenXml;
    using DocumentFormat.OpenXml.Packaging;
    using DocumentFormat.OpenXml.Spreadsheet;

    using global::Konfiguration.Export;

    /// <summary>
    /// Class to help to build an Xlsx File
    /// </summary>
    public static class XlsxFormat
    {
        /// <summary>
        /// Creates the workbook
        /// </summary>
        /// <param name="fileName">Filename of the workbook</param>
        /// <returns>Spreadsheet created</returns>
        private static SpreadsheetDocument CreateWorkbook(string fileName)
        {
            SpreadsheetDocument spreadSheet = SpreadsheetDocument.Create(fileName, SpreadsheetDocumentType.Workbook, false);

            spreadSheet.AddWorkbookPart();
            spreadSheet.WorkbookPart.Workbook = new Workbook();
            spreadSheet.WorkbookPart.Workbook.Save();

            SharedStringTablePart sharedStringTablePart = spreadSheet.WorkbookPart.AddNewPart<SharedStringTablePart>();
            sharedStringTablePart.SharedStringTable = new SharedStringTable();
            sharedStringTablePart.SharedStringTable.Save();

            spreadSheet.WorkbookPart.Workbook.Sheets = new Sheets();
            spreadSheet.WorkbookPart.Workbook.Save();

            WorkbookStylesPart workbookStylesPart = spreadSheet.WorkbookPart.AddNewPart<WorkbookStylesPart>();
            workbookStylesPart.Stylesheet = new Stylesheet();
            workbookStylesPart.Stylesheet.Save();

            return spreadSheet;
        }

        /// <summary>
        /// Load the workbook
        /// </summary>
        /// <param name="fileName">Filename of the workbook</param>
        /// <returns>Spreadsheet loaded</returns>
        private static SpreadsheetDocument OpenWorkbook(string fileName)
        {
            return SpreadsheetDocument.Open(fileName, true);
        }

        /// <summary>
        /// Adds a new worksheet to the workbook
        /// </summary>
        /// <param name="spreadsheet">Spreadsheet to use</param>
        /// <param name="name">Name of the worksheet</param>
        /// <returns>True if succesful</returns>
        private static bool AddWorksheet(SpreadsheetDocument spreadsheet, string name)
        {
            Sheets sheets = spreadsheet.WorkbookPart.Workbook.GetFirstChild<Sheets>();
            Sheet sheet;
            WorksheetPart worksheetPart;

            worksheetPart = spreadsheet.WorkbookPart.AddNewPart<WorksheetPart>();
            worksheetPart.Worksheet = new Worksheet(new SheetData());
            worksheetPart.Worksheet.Save();

            sheet = new Sheet
            {
                Id = spreadsheet.WorkbookPart.GetIdOfPart(worksheetPart),
                SheetId = (uint)(spreadsheet.WorkbookPart.Workbook.Sheets.Count() + 1),
                Name = name
            };
            sheets.Append(sheet);

            spreadsheet.WorkbookPart.Workbook.Save();

            return true;
        }

        /// <summary>
        /// Get the first worksheet element
        /// </summary>
        /// <param name="spreadsheet">Spreadsheet to use</param>
        /// <returns>First Worksheet</returns>
        private static Worksheet FirstWorksheet(SpreadsheetDocument spreadsheet)
        {
            return spreadsheet.WorkbookPart.WorksheetParts.First().Worksheet;
        }

        /// <summary>
        /// Adds the basic styles to the workbook
        /// </summary>
        /// <param name="spreadsheet">Spreadsheet to use</param>
        /// <returns>True if succesful</returns>
        private static bool AddBasicStyles(SpreadsheetDocument spreadsheet)
        {
            Stylesheet stylesheet = spreadsheet.WorkbookPart.WorkbookStylesPart.Stylesheet;

            stylesheet.InsertAt(new NumberingFormats(), 0);

            stylesheet.InsertAt(new Fonts(), 1);
            stylesheet.GetFirstChild<Fonts>().InsertAt<Font>(new Font
            {
                FontSize = new FontSize { Val = 11 },
                FontName = new FontName { Val = "Calibri" }
            }, 0);

            stylesheet.GetFirstChild<Fonts>().InsertAt<Font>(new Font
            {
                FontSize = new FontSize { Val = 11 },
                FontName = new FontName { Val = "Calibri" },
                Color = new Color { Rgb = HexBinaryValue.FromString("FFF00000") }
            }, 1);

            stylesheet.InsertAt(new Fills(), 2);
            stylesheet.GetFirstChild<Fills>().InsertAt<Fill>(new Fill
            {
                PatternFill = new PatternFill { PatternType = new EnumValue<PatternValues> { Value = PatternValues.None } }
            }, 0);


            // Dummy
            stylesheet.GetFirstChild<Fills>().InsertAt<Fill>(new Fill
            {
                PatternFill = new PatternFill { PatternType = new EnumValue<PatternValues> { Value = PatternValues.None } }
            }, 1);

            stylesheet.InsertAt(new Borders(), 3);
            stylesheet.GetFirstChild<Borders>().InsertAt<Border>(new Border
            {
                LeftBorder = new LeftBorder(),
                RightBorder = new RightBorder(),
                TopBorder = new TopBorder(),
                BottomBorder = new BottomBorder(),
                DiagonalBorder = new DiagonalBorder()
            }, 0);

            stylesheet.InsertAt(new CellStyleFormats(), 4);
            stylesheet.GetFirstChild<CellStyleFormats>().InsertAt<CellFormat>(new CellFormat
            {
                NumberFormatId = 0,
                FontId = 0,
                FillId = 0,
                BorderId = 0,
            }, 0);

            stylesheet.InsertAt(new CellFormats(), 5);

            stylesheet.GetFirstChild<CellFormats>().InsertAt<CellFormat>(new CellFormat
            {
                FormatId = 0,
                NumberFormatId = 0
            }, 0);

            stylesheet.GetFirstChild<CellFormats>().InsertAt<CellFormat>(new CellFormat
            {
                FormatId = 0,
                NumberFormatId = 0,
                FontId = 1,
                FillId = 0,
                BorderId = 0
            }, 1);

            stylesheet.Save();

            return true;
        }

        /// <summary>
        /// Adds a cell style foreground color
        /// </summary>
        /// <param name="spreadsheet">Spreadsheet to use</param>
        /// <param name="rgbColor">Color as rgb hex code</param>
        /// <param name="save">Save the shared string table</param>
        /// <returns>Cell style index</returns>
        private static int AddCellStylesForegroundColor(SpreadsheetDocument spreadsheet, HexBinaryValue rgbColor, bool save)
        {
            Stylesheet stylesheet = spreadsheet.WorkbookPart.WorkbookStylesPart.Stylesheet;

            Fill fill = new Fill
            {
                PatternFill = new PatternFill
                {
                    PatternType = new EnumValue<PatternValues> { Value = PatternValues.Solid },
                    ForegroundColor = new ForegroundColor { Rgb = rgbColor }
                }
            };

            bool found = false;
            int fillIndex = 0;
            foreach (Fill item in stylesheet.GetFirstChild<Fills>().Elements<Fill>())
            {
                if (item.PatternFill.PatternType.Value.Equals(fill.PatternFill.PatternType.Value))
                {
                    if (item.PatternFill.ForegroundColor.Rgb.Value.Equals(fill.PatternFill.ForegroundColor.Rgb.Value))
                    {
                        found = true;
                        break;
                    }
                }

                fillIndex++;
            }

            if (!found)
            {
                stylesheet.GetFirstChild<Fills>().InsertAt<Fill>(fill, fillIndex);
            }

            CellFormat cellFormat = new CellFormat
            {
                FillId = (uint)fillIndex
            };

            found = false;
            int cellFormatIndex = 0;
            foreach (CellFormat item in stylesheet.GetFirstChild<CellFormats>().Elements<CellFormat>())
            {
                if (item.FillId == null)
                {
                    cellFormatIndex++;
                    continue;
                }

                if (item.FillId.Value.Equals(cellFormat.FillId.Value))
                {
                    found = true;
                    break;
                }

                cellFormatIndex++;
            }

            if (!found)
            {
                stylesheet.GetFirstChild<CellFormats>().InsertAt<CellFormat>(cellFormat, cellFormatIndex);
            }

            if (save)
            {
                stylesheet.Save();
            }

            return cellFormatIndex;
        }

        /// <summary>
        /// Add a single string to shared strings table.
        /// Shared string table is created if it doesn't exist.
        /// </summary>
        /// <param name="spreadsheet">Spreadsheet to use</param>
        /// <param name="stringItem">string to add</param>
        /// <param name="save">Save the shared string table</param>
        /// <returns></returns>
        private static bool AddSharedString(SpreadsheetDocument spreadsheet, string stringItem, bool save)
        {
            SharedStringTable sharedStringTable = spreadsheet.WorkbookPart.SharedStringTablePart.SharedStringTable;

            if (0 == sharedStringTable.Where(item => item.InnerText == stringItem).Count())
            {
                sharedStringTable.AppendChild(new SharedStringItem(new Text(stringItem)));

                if (save)
                {
                    sharedStringTable.Save();
                }
            }

            return true;
        }

        /// <summary>
        /// Returns the index of a shared string.
        /// </summary>
        /// <param name="spreadsheet">Spreadsheet to use</param>
        /// <param name="stringItem">String to search for</param>
        /// <returns>Index of a shared string. -1 if not found</returns>
        private static int IndexOfSharedString(SpreadsheetDocument spreadsheet, string stringItem)
        {
            SharedStringTable sharedStringTable = spreadsheet.WorkbookPart.SharedStringTablePart.SharedStringTable;
            bool found = false;
            int index = 0;

            foreach (SharedStringItem sharedString in sharedStringTable.Elements<SharedStringItem>())
            {
                if (sharedString.InnerText == stringItem)
                {
                    found = true;
                    break;
                }
                index++;
            }

            if (found)
            {
                return index;
            }

            return -1;
        }

        /// <summary>
        /// Get the index of last row element
        /// </summary>
        /// <param name="worksheet">Worksheet to use</param>
        /// <returns>Index of last row</returns>
        private static UInt32Value NextRowIndex(Worksheet worksheet)
        {
            if (worksheet.GetFirstChild<SheetData>().Elements<Row>().Count() != 0)
            {
                return worksheet.GetFirstChild<SheetData>().Elements<Row>().Last<Row>().RowIndex + 1;
            }

            return 1;
        }

        /// <summary>
        /// Converts a column number to column name (i.e. A, B, C..., AA, AB...)
        /// </summary>
        /// <param name="columnIndex">Index of the column</param>
        /// <returns>Column name</returns>
        private static string ColumnNameFromIndex(uint columnIndex)
        {
            string columnName = "";

            while (columnIndex > 0)
            {
                uint remainder = (columnIndex - 1) % 26;
                columnName = Convert.ToChar(65 + remainder).ToString() + columnName;
                columnIndex = (uint)((columnIndex - remainder) / 26);
            }

            return columnName;
        }

        /// <summary>
        /// Sets a cell value. The row and the cell are created if they do not exist. If the cell exists, the contents of the cell is overwritten
        /// </summary>
        /// <param name="worksheet">Worksheet to use</param>
        /// <param name="columnIndex">Index of the column</param>
        /// <param name="rowIndex">Index of the row</param>
        /// <param name="valueType">Type of the value</param>
        /// <param name="value">The actual value</param>
        /// <param name="styleIndex">Index of the style to use. Null if no style is to be defined</param>
        /// <param name="save">Save the worksheet?</param>
        /// <returns>True if succesful</returns>
        private static bool SetCellValue(Worksheet worksheet, uint columnIndex, uint rowIndex, CellValues valueType, string value, uint? styleIndex, bool save)
        {
            SheetData sheetData = worksheet.GetFirstChild<SheetData>();
            Row row;
            Row previousRow = null;
            Cell cell;
            Cell previousCell = null;
            Columns columns;
            Column previousColumn = null;
            string cellAddress = ColumnNameFromIndex(columnIndex) + rowIndex;

            if (sheetData.Elements<Row>().Where(item => item.RowIndex == rowIndex).Count() != 0)
            {
                row = sheetData.Elements<Row>().Where(item => item.RowIndex == rowIndex).First();
            }
            else
            {
                row = new Row { RowIndex = rowIndex };

                for (uint counter = rowIndex - 1; counter > 0; counter--)
                {
                    previousRow = sheetData.Elements<Row>().Where(item => item.RowIndex == counter).FirstOrDefault();
                    if (previousRow != null)
                    {
                        break;
                    }
                }

                sheetData.InsertAfter(row, previousRow);
            }

            if (row.Elements<Cell>().Where(item => item.CellReference.Value == cellAddress).Count() > 0)
            {
                cell = row.Elements<Cell>().Where(item => item.CellReference.Value == cellAddress).First();
            }
            else
            {
                for (uint counter = columnIndex - 1; counter > 0; counter--)
                {
                    previousCell = row.Elements<Cell>().Where(item => item.CellReference.Value == ColumnNameFromIndex(counter) + rowIndex).FirstOrDefault();
                    if (previousCell != null)
                    {
                        break;
                    }
                }

                cell = new Cell { CellReference = cellAddress, StyleIndex = styleIndex };

                row.InsertAfter(cell, previousCell);
            }

            columns = worksheet.Elements<Columns>().FirstOrDefault();
            if (columns == null)
            {
                columns = worksheet.InsertAt(new Columns(), 0);
            }

            if (columns.Elements<Column>().Where(item => item.Min == columnIndex).Count() == 0)
            {
                for (uint counter = columnIndex - 1; counter > 0; counter--)
                {
                    previousColumn = columns.Elements<Column>().Where(item => item.Min == counter).FirstOrDefault();
                    if (previousColumn != null)
                    {
                        break;
                    }
                }

                columns.InsertAfter(new Column
                {
                    Min = columnIndex,
                    Max = columnIndex,
                    CustomWidth = true,
                    Width = 9
                }, previousColumn);
            }

            cell.CellValue = new CellValue(value);
            if (styleIndex != null)
            {
                cell.StyleIndex = styleIndex;
            }

            if (valueType != CellValues.Date)
            {
                cell.DataType = new EnumValue<CellValues>(valueType);
            }

            if (save)
            {
                worksheet.Save();
            }

            return true;
        }

        /// <summary>
        /// Sets a string value to a cell
        /// </summary>
        /// <param name="spreadsheet">Spreadsheet to use</param>
        /// <param name="worksheet">Worksheet to use</param>
        /// <param name="columnIndex">Index of the column</param>
        /// <param name="rowIndex">Index of the row</param>
        /// <param name="stringValue">String value to set</param>
        /// <param name="useSharedString">Use shared strings? If true and the string isn't found in shared strings, it will be added</param>
        /// <param name="styleIndex">Style to use</param>
        /// <param name="save">Save the worksheet</param>
        /// <returns>True if succesful</returns>
        public static bool SetCellValue(SpreadsheetDocument spreadsheet, Worksheet worksheet, uint columnIndex, uint rowIndex, string stringValue, bool useSharedString, uint? styleIndex, bool save)
        {
            string columnValue = stringValue;
            CellValues cellValueType;

            if (useSharedString)
            {
                if (IndexOfSharedString(spreadsheet, stringValue) == -1)
                {
                    AddSharedString(spreadsheet, stringValue, true);
                }

                columnValue = IndexOfSharedString(spreadsheet, stringValue).ToString();
                cellValueType = CellValues.SharedString;
            }
            else
            {
                cellValueType = CellValues.String;
            }

            return SetCellValue(worksheet, columnIndex, rowIndex, cellValueType, columnValue, styleIndex, save);
        }

        /// <summary>
        /// Sets a cell hyperlink
        /// </summary>
        /// <param name="spreadsheet">Spreadsheet to use</param>
        /// <param name="worksheet">Worksheet to use</param>
        /// <param name="columnIndex">Address of the cell</param>
        /// <param name="rowIndex">Index of the row</param>
        /// <param name="linkValue">Link for the cell</param>
        /// <param name="save">Save the worksheet</param>
        /// <returns>True if succesful</returns>
        public static bool SetCellHyperlink(SpreadsheetDocument spreadsheet, Worksheet worksheet, uint columnIndex, uint rowIndex, string linkValue, bool save)
        {
            HyperlinkRelationship hyperlinkRelationship = SetHyperlinkRelationship(worksheet, linkValue);

            Hyperlinks hyperlinks;
            if (!worksheet.Elements<Hyperlinks>().Any())
            {
                hyperlinks = new Hyperlinks();
                worksheet.InsertBefore(hyperlinks, worksheet.Descendants<PageMargins>().FirstOrDefault<PageMargins>());
            }
            else
            {
                hyperlinks = worksheet.Elements<Hyperlinks>().First<Hyperlinks>();
            }

            Hyperlink hyperlink = new Hyperlink { Reference = ColumnNameFromIndex(columnIndex) + rowIndex, Id = hyperlinkRelationship.Id };
            hyperlinks.Append(hyperlink);

            if (save)
            {
                worksheet.Save();
            }

            return true;
        }

        /// <summary>
        /// Sets a cell hyperlink relationship
        /// </summary>
        /// <param name="worksheet">Worksheet to use</param>
        /// <param name="link">Link for the cell</param>
        /// <returns>Hyperlink relationship object</returns>
        private static HyperlinkRelationship SetHyperlinkRelationship(Worksheet worksheet, string link)
        {
            return worksheet.WorksheetPart.AddHyperlinkRelationship(new Uri(link, UriKind.Absolute), true);
        }

        /// <summary>
        /// The write xlsx values.
        /// </summary>
        /// <param name="fileName">
        /// The file Name.
        /// </param>
        /// <param name="values">
        /// The values.
        /// </param>
        /// <param name="separator">
        /// The separator.
        /// </param>
        public static void WriteValues(string fileName, string values, string separator)
        {
            SpreadsheetDocument spreadsheetDocument = CreateWorkbook(fileName);
            AddBasicStyles(spreadsheetDocument);
            AddWorksheet(spreadsheetDocument, "sheet1");

            Worksheet worksheet = FirstWorksheet(spreadsheetDocument);

            uint rowIndex = NextRowIndex(worksheet);
            uint columnIndex = 1;

            string[] splittedValueString = values.Split(new[] { separator }, StringSplitOptions.None);

            for (int i = 0; i < splittedValueString.Count(); i++)
            {
                string cellValue = splittedValueString[i];
                uint cellStyleIndex = 0;
                bool colorCell = false;

                if (columnIndex - 1 == KonfigExportWorkflow.Instance.eIdxColor)
                {
                    if (!cellValue.IndexOf(',').Equals(-1))
                    {
                        colorCell = true;

                        int[] rgbValue = new int[3];

                        int j = 0;
                        foreach (string value in cellValue.Split(','))
                        {
                            int.TryParse(value, out rgbValue[j]);

                            j++;
                        }

                        // Alpha Red Green Blue Color Value
                        HexBinaryValue rgbColor = HexBinaryValue.FromString(string.Format("FF{0:X2}{1:X2}{2:X2}", rgbValue[0], rgbValue[1], rgbValue[2]));

                        cellStyleIndex = (uint)AddCellStylesForegroundColor(spreadsheetDocument, rgbColor, true);
                    }
                }

                if (colorCell)
                {
                    SetCellValue(spreadsheetDocument, worksheet, columnIndex, rowIndex, string.Empty, true, cellStyleIndex, true);
                }
                else
                {
                    SetCellValue(spreadsheetDocument, worksheet, columnIndex, rowIndex, cellValue, true, cellStyleIndex, true);
                }

                if (KonfigExportCompact.Instance.eIdxImagePathDefault != -1
                    && KonfigExportCompact.Instance.eIdxImagePathDefault < splittedValueString.Count())
                {
                    if (splittedValueString[KonfigExportCompact.Instance.eIdxImagePathDefault].Equals(cellValue))
                    {
                        if (File.Exists(cellValue))
                        {
                            SetCellHyperlink(spreadsheetDocument, worksheet, columnIndex, rowIndex, cellValue, true);
                        }
                    }
                }

                columnIndex++;
            }

            worksheet.Save();
        }
    }
}


After the repair, the file is opened, and it's all there, just the links to the images were removed.

Have been a few hours at google searched but found nothing.

Does anyone know the Problem?

OpenXMLSDK losing my format after mail merge

$
0
0

Hi

I am using OpenXMLSDK for mail merge and replace the Field Code with text. There is no problem with the replace as it replaces all the filed correctly in headers, footers and main document. The problem is after mail merge the document moves 2 to 3 lines up. I have address field at the first page and I can see the address field has moved up a bit after mail merge, but in the template it looks correct.

When I click the header and footer of the document after mail merge the document shuffles and it retains the correct format. I can see the document have come down and retained the correct format after this action. 

So why it cannot retain the format when I open the document. I don't want to click the header or footer to shuffle and retain my format. Can anyone help.

Thank you.

Jayakumar HCL


Best way to import from XML

$
0
0

I have to preface this by saying this is really my first time working with moving data though XML and transposing it into a word document. 

Currently the place I work at just started using XML to shift data from one factory to another.  We are now in the process of converting everything to word.  I wondered if there was an easy way to read data from an XML file, find the data that I want and then transpose that data onto a document.  I'm looking for a place that a beginner should get started with, I know there are some questions like that on here already.  I'm just looking for the first step on where to go. 


Read Excel file using OpenXML by Columnwise

$
0
0

hi all,

I  m having miss matched counts of columns in my excel EX: my excel file header row contains 10 columns and forecoming 5 rows having same 10 columns but the next row contains 12 columns .

So I feel better if I can read excel columnwise ,so plase help me to resolve this problem.

Thanks in advance


 

XML File Won't Load

$
0
0

I have tried to load xml many different ways and have now started to do it this way: 

      Dim advDocument As New XmlDocument
        Dim reader As New XmlTextReader("C:/temp2/A403963.xml")
        reader.WhitespaceHandling = WhitespaceHandling.None
        reader.MoveToContent()
        reader.Read()
        advDocument.Load(reader)

I errors on the advDocument.Load(reader) line.  I had done it before as a simple:

      Dim advDocument As New XmlDocument
        advDocument.Load("C:/temp2/a403963.xml")

But that doesn't seem to work either.  Any ideas?

How to insert Word 2013 Start/End tag type Content Controls using OpenXML sdk

$
0
0

Is there any way to create a document with Start/End tag type  a content control using open XML sdk?


Antony

Convert doc/docx to html

$
0
0

Guys,

I want to convert my word document(doc/docx) to html.

Is it possible using .net and openXML library.

Microsoft.Office.Interop.Word has this functionality.


markand

Open Xml combining multiple word document into one

$
0
0

Hi

I have written below code the combine multiple word DOCX to single one.

But the merged document has lot of space and if i merge 2 - 24 page document into one it is not produced as 48 pages.

because of extra spaces it appends, it becomes 82 pages somehow.

Please advice and help on this. Thanks, Vikas

private static void MergeWordDocs()
{
    string sourceFolder = @"C:\Test\MergeDocs\";
    string targetFolder = @"C:\Test\";

    string altChunkIdBase = "acID";
    int altChunkCounter = 1;
    string altChunkId = altChunkIdBase + altChunkCounter.ToString();

    MainDocumentPart wdDocTargetMainPart = null;
    Document docTarget = null;
    AlternativeFormatImportPartType afType;
    AlternativeFormatImportPart chunk = null;
    AltChunk ac = null;

    using (WordprocessingDocument wdPkgTarget = WordprocessingDocument.Create(targetFolder + "finalDoc.docx", DocumentFormat.OpenXml.WordprocessingDocumentType.Document, true))
    {
        wdDocTargetMainPart = wdPkgTarget.MainDocumentPart;
        if (wdDocTargetMainPart == null)
        {
            wdDocTargetMainPart = wdPkgTarget.AddMainDocumentPart();
            Document wdDoc = new Document(
                new Body(
                    new Paragraph(                    
                        ),                    
                    new SectionProperties(
                    new SectionType() { Val = SectionMarkValues.NextPage },
                    new PageNumberType { Start = 1 },
                    new SpacingBetweenLines() { After = "0"}
                        )
                        )
                    );
            wdDocTargetMainPart.Document = wdDoc;
        }
        docTarget = wdDocTargetMainPart.Document;
        SectionProperties secPropLast = docTarget.Body.Descendants<SectionProperties>().Last();
        SectionProperties secPropNew = (SectionProperties)secPropLast.CloneNode(true);

        Paragraph lastParaTarget = (Paragraph)docTarget.Body.Descendants<Paragraph>().Last();
        ParagraphProperties paraPropTarget = lastParaTarget.ParagraphProperties;
        if (paraPropTarget == null)
        {
            paraPropTarget = new ParagraphProperties();
        }
        paraPropTarget.Append(secPropNew);

        lastParaTarget.InsertAt(paraPropTarget, 0);
        SpacingBetweenLines spacing = new SpacingBetweenLines() { After = "0" };
        ParagraphProperties paraProps = null;
        System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(sourceFolder);
        IEnumerable<System.IO.FileInfo> docFiles = di.EnumerateFiles();
        foreach (System.IO.FileInfo fi in docFiles)
        {
            using (WordprocessingDocument pkgSourceDoc = WordprocessingDocument.Open(fi.FullName, true))
            {
                IEnumerable<HeaderPart> partsHeader = pkgSourceDoc.MainDocumentPart.GetPartsOfType<HeaderPart>();
                IEnumerable<FooterPart> partsFooter = pkgSourceDoc.MainDocumentPart.GetPartsOfType<FooterPart>();

                if (partsHeader.Count() > 0 || partsFooter.Count() > 0)
                {
                    Body sourceBody = pkgSourceDoc.MainDocumentPart.Document.Body;
                    SectionProperties docSectionBreak = sourceBody.Descendants<SectionProperties>().Last();
                    SectionProperties copySectionBreak = (SectionProperties)docSectionBreak.CloneNode(true);
                    Paragraph lastpara = sourceBody.Descendants<Paragraph>().Last();
                    paraProps = lastpara.ParagraphProperties;
                    if (paraProps == null)
                    {
                        paraProps = new ParagraphProperties();
                        lastpara.Append(paraProps);
                    }
                    paraProps.Append(copySectionBreak);
                }
                pkgSourceDoc.MainDocumentPart.Document.Save();
            }

            afType = AlternativeFormatImportPartType.WordprocessingML;
            chunk = wdDocTargetMainPart.AddAlternativeFormatImportPart(afType, altChunkId);
            System.IO.FileStream fsSourceDocument = new System.IO.FileStream(fi.FullName, System.IO.FileMode.Open);
            chunk.FeedData(fsSourceDocument);
            ac = new AltChunk();
            ac.Id = altChunkId;
                
            docTarget.Body.InsertAfter(ac, docTarget.Body.Descendants<Paragraph>().Last());
            docTarget.Save();
            altChunkCounter += 1;
            altChunkId = altChunkIdBase + altChunkCounter.ToString();
            chunk = null;
            ac = null;
        }
    }

}

How to hide grid lines by using open xml

$
0
0

Hi

   Actually i have a excel template, so i will copy the template and i will fill the data by using open xml, so that is fine, but i want to hide the grid line in each sheet, so i tried using below code, but i could not able to do  it, because"Sheets" is always null so it won't enter into the if condition, can you tell me is any other way there to hide the grid lines

using (var document = SpreadsheetDocument.Open(newFileName, true))
            {
SheetViews sheets = document.WorkbookPart.Workbook.GetFirstChild<SheetViews>();
                    if (sheets != null)
                    {
                        foreach (SheetView sheet in sheets )
                        {
                        }
                    }
}

Filling Excel Pivot sheet dynamically with C# DataTable

$
0
0

Hello,

I have received xlsx file with data in one sheet and built pivot in another one.

I need to insert/update dynamically table data from C# application's DataTable. Problem is that Pivot sheet's Datasource is based on range selected in the data sheet which row count is dynamic.

I'm using OpenXml SDK Package and filling the cells in following way:

foreach (System.Data.DataRow dsrow in table.Rows)
{
    DocumentFormat.OpenXml.Spreadsheet.Row newRow = new DocumentFormat.OpenXml.Spreadsheet.Row();
    foreach (String col in columns)
    {
        DocumentFormat.OpenXml.Spreadsheet.Cell cell = new DocumentFormat.OpenXml.Spreadsheet.Cell();

        if (DataEntryValidationManager.IsNumeric(dsrow[col]))
            cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.Number;
        else
            cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.String;

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

    sheetData.AppendChild(newRow);
}

How can I make sure the range for Pivot DataSource is selected correctly according to rowcount after I fill data?

Thank you in advance,

Shabtai




Issue in programmatic Mail-Merge with word document using open-xml, asp.net, C#.

$
0
0
Issue in programmatic Mail-Merge with word document using open-xml, asp.net, C#.

In one of our project we want to programmatically do mail-merge. That mean, we have an existing word document with mail-merge fields in it and when we run our code, values from table will be replaced in mail-merge fields of word document and the document will be saved with a new name.

The project is developed using asp.net, C# and open-xml.

Our code works, but not giving guaranteed results. That is, in one word document some fields get merged but few other do not. Please refer to attached code extract, we are using. The issue is for some of the nodes in nodelist (xnodeList), child nodes, data nodes getting generated as null. So getting Null reference exception.

Please suggest how to resolve this issue by suggesting a correction in code or any other method altogether. Please note we cannot use interops etc. (Microsoft.Office.Interop.Word) because this is a web application and we cannot install MS-Office on application server.


////////////////////////// CODE ////////////////////////////////////////

    using System.IO;
    using System.Xml;
    using DocumentFormat.OpenXml.Packaging;
    using System.IO.Packaging;
    using System.Xml.Linq;
    using WordDocument = DocumentFormat.OpenXml.Wordprocessing;
    protected void mail_merge_file1()
        {
    
      FileInfo fi;
     Object oTemplatePath = AppConstants.TemplatesUpload + hdnTemplatePath.Value.ToString().Trim();
    
    fi = new FileInfo(oTemplatePath.ToString());
    oFileName = lstActualFilePath[0].FilePath + fi.Name.ToString().Replace(fi.Extension, "MM") + fi.Extension;
    // if file exists
    if (System.IO.File.Exists(oTemplatePath.ToString()))
                    {
    
                        XmlNamespaceManager nsManager = new XmlNamespaceManager(nt);
    
                        nsManager.AddNamespace("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main");
                        PackagePart packagePart;
                        XmlNodeList nodes;
                        XmlNodeList nodes1;
                        XmlNode parentnodes;
                        XmlNode childnode;
                        XmlNode Datanode;
                        string columnname;
                        int N = 1;
                        int br = 1;
                        string strDateTimeFormat = string.Empty;
                        string strDateTimeString;
                        int intIndexofDatestart;
                        string strrootnode;
                        XmlNode root;
    
                        File.Copy(oTemplatePath.ToString(), oFileName.ToString(), true);
                        
                        // open file , read the contents of file into an byte array
                        byte[] sourceBytestemp = File.ReadAllBytes(oFileName.ToString());
                        using (MemoryStream _workingMemoryStream = new MemoryStream())
                        {
                            // Load block of bytes into memory
                            _workingMemoryStream.Write(sourceBytestemp, 0, sourceBytestemp.Length);
                            using (WordprocessingDocument wordDocument = WordprocessingDocument.Open(_workingMemoryStream, true))
                            {
                                XElement newBody = XElement.Parse(wordDocument.MainDocumentPart.Document.Body.OuterXml);
                                // Delete MailMerge Data Source Part
                                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                                {
                                    //populate all nodes of mergefields from the file
                                    IList<XElement> xnodeList = (from el in newBody.Descendants()
                                        //select el).ToList();
                                        where el.Name.LocalName == "t" && el.Value.StartsWith("«")
                                        select el).ToList();
                                    // fetch each node 1 by 1,remove child nodes and replace data nodes's value with the value of the record.    
                                    foreach (XElement xnode in xnodeList)
                                    {
                                        columnname = xnode.Value.ToString().Substring(1, xnode.Value.ToString().Length - 2);
                                        if (ds.Tables[0].Columns.Contains(columnname))
                                        {
                                            
                                            XElement xchildnode = (XElement)xnode.Parent.NextNode;
                                            //below line is getting exception as xchildnode is getting generated "null" value in case of some nodes/columns (xnode).
                                            xchildnode.Remove();
                                            
                                            XElement xDatanode = (XElement)((XElement)xnode.Parent.PreviousNode.PreviousNode).LastNode;
                                            if (((XElement)xDatanode).Value.ToString().Contains("\\"))
                                            {
                                                if (ds.Tables[0].Columns[columnname] != null)
                                                {
                                                    intIndexofDatestart = ((XElement)((XElement)xnode.Parent.PreviousNode.PreviousNode).LastNode).Value.ToString().IndexOf("\\");
    
                                                    strDateTimeString = ((XElement)((XElement)xnode.Parent.PreviousNode.PreviousNode).LastNode).Value.ToString().Trim();
                                                    switch (xDatanode.Value.ToString().Substring(intIndexofDatestart, 2))
                                                    {
                                                        case "\\@":
                                                            strDateTimeFormat = strDateTimeString.Substring(intIndexofDatestart + 3, strDateTimeString.Length - (intIndexofDatestart + 4));
                                                            break;
                                                        case "\\#":
                                                            strDateTimeFormat = strDateTimeString.Substring(intIndexofDatestart + 2, strDateTimeString.Length - (intIndexofDatestart + 2));
                                                            break;
                                                    }
                                                    if (ds.Tables[0].Columns[columnname].DataType == Type.GetType("System.DateTime"))
                                                    {
                                                        if (Convert.IsDBNull(ds.Tables[0].Rows[i][columnname]))
                                                        {
                                                            ((XElement)xnode).Value = "";
                                                        }
                                                        else
                                                        {
                                                            ((XElement)xnode).Value  = Convert.ToDateTime(ds.Tables[0].Rows[i][columnname].ToString()).
                ToString(strDateTimeFormat);
                                                        }
                                                    }
                                                    else
                                                    {
                                                        if (Convert.IsDBNull(ds.Tables[0].Rows[i][columnname]))
                                                        {
                                                            ((XElement)xnode).Value = "";
                                                        }
                                                        else
                                                        {
                                                            /*new code*/
                                                            ((XElement)xnode).Value = ds.Tables[0].Rows[i][columnname].ToString();
                                                            /*new code ends*/
                                                        }
    
                                                    }
                                                }
                                            }
                                            else
                                            {
                                                if (Convert.IsDBNull(ds.Tables[0].Rows[i][columnname]))
                                                {
                                                    ((XElement)xnode).Value = "";
                                                }
                                                else
                                                {
                                                    ((XElement)xnode).Value = ds.Tables[0].Rows[i][columnname].ToString();
                                                }
                                            }
    
                                            for (int k = 0; k < 3; k++)
                                            {
                                                xchildnode = (XElement)xnode.Parent.PreviousNode;
                                                xchildnode.Remove();
                                            }
    
                                        }
    
                                        ///adding page break .
                                        ///
                                        if (i + 1 < ds.Tables[0].Rows.Count)
                                        {
    
                                            IList<XElement> xnodes = (from el in newBody.Descendants()
                                                                      //select el).ToList();
                                                                      where el.Name.LocalName == "sectPr"
                                                                      select el).ToList();
                                            /// end Adding document for next row
                                        }
                                        else
                                        {
                                            wordDocument.MainDocumentPart.Document.Body = new WordDocument.Body(newBody.ToString());
                                            wordDocument.MainDocumentPart.Document.Save();
                                        }
    
                                    }
                                }
                                DocumentSettingsPart settingsPart = wordDocument.MainDocumentPart.GetPartsOfType<DocumentSettingsPart>().First();
                                // Delete reference to Mail Merge Data sources
                                XElement settings = XElement.Parse(settingsPart.RootElement.OuterXml);
                                IList<XElement> mailMergeElements =
                                    (from el in settings.Descendants()
                                     where el.Name.LocalName == ("mailMerge")
                                     select el).ToList();
    
                                foreach (XElement field in mailMergeElements)
                                {
                                    field.Remove();
                                }
                                settingsPart.RootElement.InnerXml = settings.ToString();
                                settingsPart.RootElement.Save();
    
                                // Save in output directory
                                // Create a new document based on updated template
                                using (FileStream fileStream = new FileStream(oFileName.ToString(), FileMode.Create))
                                {
                                    _workingMemoryStream.WriteTo(fileStream);
                                }
                            }
                        }
                    }
    
    
        }   

           

cannot convert xlsm to xlsx using ChangeDocumentType

$
0
0
 i tried to use openxml's changedocumenttype to convert xlsm to xlsx file,
 but when it was done, i cannot open it , the office showed me the xlsx file was broken.

 who can tell me  why was that? this is the code:

    //convert xlsm to xlsx
    using (SpreadsheetDocument myDoc = SpreadsheetDocument.Open(xlsmPath, true))
    {
         myDoc.ChangeDocumentType(SpreadsheetDocumentType.Workbook);
    }

Need suggestion to impove the performance to export data to excel

$
0
0

Following is my current code using  excel interop way

var data = new object[rows, columns];
for (var row = 1; row <= rows; row++)
{
for (var column = 1; column <= columns; column++)
{
data[row - 1, column - 1] = "Test";
}
}
var startCell = (Range)worksheet.Cells[1, 1];
var endCell = (Range)worksheet.Cells[rows, columns];
var writeRange = worksheet.Range[startCell, endCell];
writeRange.Value2 = data;

my question here   is there a way to do this using openxml


Perfomace issue in export to excel

$
0
0

Hello all,

i want to write 100 k records to excel template with in less than 50 sec , by using following code we are able to achieve this, but this code uses the excel interop libraries.

is there a way to achieve this range insert using open xml

var data = new object[rows, columns];
for (var row = 1; row <= rows; row++)
{
for (var column = 1; column <= columns; column++)
{
data[row - 1, column - 1] = "Test";
}
}
var startCell = (Range)worksheet.Cells[1, 1];
var endCell = (Range)worksheet.Cells[rows, columns];
var writeRange = worksheet.Range[startCell, endCell];
writeRange.Value2 = data;

Issue in programmatic Mail-Merge with word document using open-xml, asp.net, C#.

$
0
0
Issue in programmatic Mail-Merge with word document using open-xml, asp.net, C#.

In one of our project we want to programmatically do mail-merge. That mean, we have an existing word document with mail-merge fields in it and when we run our code, values from table will be replaced in mail-merge fields of word document and the document will be saved with a new name.

The project is developed using asp.net, C# and open-xml.

Our code works, but not giving guaranteed results. That is, in one word document some fields get merged but few other do not. Please refer to attached code extract, we are using. The issue is for some of the nodes in nodelist (xnodeList), child nodes, data nodes getting generated as null. So getting Null reference exception.

Please suggest how to resolve this issue by suggesting a correction in code or any other method altogether. Please note we cannot use interops etc. (Microsoft.Office.Interop.Word) because this is a web application and we cannot install MS-Office on application server.


////////////////////////// CODE ////////////////////////////////////////

    using System.IO;
    using System.Xml;
    using DocumentFormat.OpenXml.Packaging;
    using System.IO.Packaging;
    using System.Xml.Linq;
    using WordDocument = DocumentFormat.OpenXml.Wordprocessing;
    protected void mail_merge_file1()
        {
    
      FileInfo fi;
     Object oTemplatePath = AppConstants.TemplatesUpload + hdnTemplatePath.Value.ToString().Trim();
    
    fi = new FileInfo(oTemplatePath.ToString());
    oFileName = lstActualFilePath[0].FilePath + fi.Name.ToString().Replace(fi.Extension, "MM") + fi.Extension;
    // if file exists
    if (System.IO.File.Exists(oTemplatePath.ToString()))
                    {
    
                        XmlNamespaceManager nsManager = new XmlNamespaceManager(nt);
    
                        nsManager.AddNamespace("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main");
                        PackagePart packagePart;
                        XmlNodeList nodes;
                        XmlNodeList nodes1;
                        XmlNode parentnodes;
                        XmlNode childnode;
                        XmlNode Datanode;
                        string columnname;
                        int N = 1;
                        int br = 1;
                        string strDateTimeFormat = string.Empty;
                        string strDateTimeString;
                        int intIndexofDatestart;
                        string strrootnode;
                        XmlNode root;
    
                        File.Copy(oTemplatePath.ToString(), oFileName.ToString(), true);
                        
                        // open file , read the contents of file into an byte array
                        byte[] sourceBytestemp = File.ReadAllBytes(oFileName.ToString());
                        using (MemoryStream _workingMemoryStream = new MemoryStream())
                        {
                            // Load block of bytes into memory
                            _workingMemoryStream.Write(sourceBytestemp, 0, sourceBytestemp.Length);
                            using (WordprocessingDocument wordDocument = WordprocessingDocument.Open(_workingMemoryStream, true))
                            {
                                XElement newBody = XElement.Parse(wordDocument.MainDocumentPart.Document.Body.OuterXml);
                                // Delete MailMerge Data Source Part
                                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                                {
                                    //populate all nodes of mergefields from the file
                                    IList<XElement> xnodeList = (from el in newBody.Descendants()
                                        //select el).ToList();
                                        where el.Name.LocalName == "t" && el.Value.StartsWith("«")
                                        select el).ToList();
                                    // fetch each node 1 by 1,remove child nodes and replace data nodes's value with the value of the record.    
                                    foreach (XElement xnode in xnodeList)
                                    {
                                        columnname = xnode.Value.ToString().Substring(1, xnode.Value.ToString().Length - 2);
                                        if (ds.Tables[0].Columns.Contains(columnname))
                                        {
                                            
                                            XElement xchildnode = (XElement)xnode.Parent.NextNode;
                                            //below line is getting exception as xchildnode is getting generated "null" value in case of some nodes/columns (xnode).
                                            xchildnode.Remove();
                                            
                                            XElement xDatanode = (XElement)((XElement)xnode.Parent.PreviousNode.PreviousNode).LastNode;
                                            if (((XElement)xDatanode).Value.ToString().Contains("\\"))
                                            {
                                                if (ds.Tables[0].Columns[columnname] != null)
                                                {
                                                    intIndexofDatestart = ((XElement)((XElement)xnode.Parent.PreviousNode.PreviousNode).LastNode).Value.ToString().IndexOf("\\");
    
                                                    strDateTimeString = ((XElement)((XElement)xnode.Parent.PreviousNode.PreviousNode).LastNode).Value.ToString().Trim();
                                                    switch (xDatanode.Value.ToString().Substring(intIndexofDatestart, 2))
                                                    {
                                                        case "\\@":
                                                            strDateTimeFormat = strDateTimeString.Substring(intIndexofDatestart + 3, strDateTimeString.Length - (intIndexofDatestart + 4));
                                                            break;
                                                        case "\\#":
                                                            strDateTimeFormat = strDateTimeString.Substring(intIndexofDatestart + 2, strDateTimeString.Length - (intIndexofDatestart + 2));
                                                            break;
                                                    }
                                                    if (ds.Tables[0].Columns[columnname].DataType == Type.GetType("System.DateTime"))
                                                    {
                                                        if (Convert.IsDBNull(ds.Tables[0].Rows[i][columnname]))
                                                        {
                                                            ((XElement)xnode).Value = "";
                                                        }
                                                        else
                                                        {
                                                            ((XElement)xnode).Value  = Convert.ToDateTime(ds.Tables[0].Rows[i][columnname].ToString()).
                ToString(strDateTimeFormat);
                                                        }
                                                    }
                                                    else
                                                    {
                                                        if (Convert.IsDBNull(ds.Tables[0].Rows[i][columnname]))
                                                        {
                                                            ((XElement)xnode).Value = "";
                                                        }
                                                        else
                                                        {
                                                            /*new code*/
                                                            ((XElement)xnode).Value = ds.Tables[0].Rows[i][columnname].ToString();
                                                            /*new code ends*/
                                                        }
    
                                                    }
                                                }
                                            }
                                            else
                                            {
                                                if (Convert.IsDBNull(ds.Tables[0].Rows[i][columnname]))
                                                {
                                                    ((XElement)xnode).Value = "";
                                                }
                                                else
                                                {
                                                    ((XElement)xnode).Value = ds.Tables[0].Rows[i][columnname].ToString();
                                                }
                                            }
    
                                            for (int k = 0; k < 3; k++)
                                            {
                                                xchildnode = (XElement)xnode.Parent.PreviousNode;
                                                xchildnode.Remove();
                                            }
    
                                        }
    
                                        ///adding page break .
                                        ///
                                        if (i + 1 < ds.Tables[0].Rows.Count)
                                        {
    
                                            IList<XElement> xnodes = (from el in newBody.Descendants()
                                                                      //select el).ToList();
                                                                      where el.Name.LocalName == "sectPr"
                                                                      select el).ToList();
                                            /// end Adding document for next row
                                        }
                                        else
                                        {
                                            wordDocument.MainDocumentPart.Document.Body = new WordDocument.Body(newBody.ToString());
                                            wordDocument.MainDocumentPart.Document.Save();
                                        }
    
                                    }
                                }
                                DocumentSettingsPart settingsPart = wordDocument.MainDocumentPart.GetPartsOfType<DocumentSettingsPart>().First();
                                // Delete reference to Mail Merge Data sources
                                XElement settings = XElement.Parse(settingsPart.RootElement.OuterXml);
                                IList<XElement> mailMergeElements =
                                    (from el in settings.Descendants()
                                     where el.Name.LocalName == ("mailMerge")
                                     select el).ToList();
    
                                foreach (XElement field in mailMergeElements)
                                {
                                    field.Remove();
                                }
                                settingsPart.RootElement.InnerXml = settings.ToString();
                                settingsPart.RootElement.Save();
    
                                // Save in output directory
                                // Create a new document based on updated template
                                using (FileStream fileStream = new FileStream(oFileName.ToString(), FileMode.Create))
                                {
                                    _workingMemoryStream.WriteTo(fileStream);
                                }
                            }
                        }
                    }
    
    
        }   

           
Viewing all 1288 articles
Browse latest View live


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