Showing posts with label Open XML SDK. Show all posts
Showing posts with label Open XML SDK. Show all posts

Tuesday, February 7, 2023

Check for comments in large word document using SAX model of Open XML SDK

Open XML SDK is the only way to work with Microsoft Office files in a managed way. It works the same regardless our code runs in a desktop application or a server-side application. The first thing to know about this SDK is its reading models. 

Why do we care about reading models?

This is important as the Open XML-based .docx, and .xlsx files are nothing but zip files with a different extension. 

  • When loading the file to memory the requirement may be 8x of the actual file size. 
  • When our code runs in memory-restricted containers it errors out with an Out of Memory Exception.

What are 2 models?

We will be seeing 2 models with an example. The example is to check for any comments in a word document.

DOM model

If we are sure the size will be small and the expanded size will fit in available memory, we can use the DOm model. The code to check for any comments in the word document goes as follows.

Tuesday, October 15, 2013

Reading empty MS Excel cells using OpenXML sdk

When we normally read the excel cells using open XML it will omit the empty cells. This is because the open xml is not keeping the information about the empty cells in the xml. We can verify this by doing a simple exercise mentioned below

  1. Open MS Excel 2007 or higher version and create a new excel document
  2. Add some text in the cell B2
  3. Save the file. Make sure you are saving in .xlsx format
  4. Once its saved change the .xlsx extension to .zip
  5. Extract the .zip file contents
  6. You can see the xml file where its recording only the value for cell B2. A1,A2,B1 are not at all mentioned in the xml.
Lets come back to the topic which is reading the excel file using Open XML sdk. The normal procedure is to iterate through each excel Row and do second iteration using Row.Elements<Cell>() .In the above mentioned file if we do the iteration the cell count will be 1 when we iterate second row. But if our requirement is to read and convert to DataSet or to create object model from excel, this behaviour may cause issues as the blank cells of excel are not considered by Open XML. I faced the same situation and below is the one which I felt more suitable to address the problem.

        public DataTable ReadFirstCell()
        {
            DataTable dataTable = new DataTable();
            string value = string.Empty;
            try
            {
                using (SpreadsheetDocument myWorkbook = SpreadsheetDocument.Open(_filePath, true))
                {
                    var sheet = myWorkbook.WorkbookPart.Workbook.GetFirstChild<Sheets>().Elements<Sheet>().First();
                    var worksheetPart = (WorksheetPart)myWorkbook.WorkbookPart.GetPartById(sheet.Id.Value);
                    IEnumerable<Row> rows = worksheetPart.Worksheet.GetFirstChild<SheetData>().Elements<Row>();
                    int RowIndex = 0;
 
                    foreach (var row in rows)
                    {
                        //Create the data table header row ie columns using first excel row.
                        if (RowIndex == 0)
                        {
                            CreateColumnsFromHeaderRow(row, dataTable);
                            RowIndex++;
                        }
                        else
                        {
                            //From second row of excel onwards, add data rows to data table.
                            IEnumerable<Cell> cells = GetCellsFromRowIncludingEmptyCells(row);
                            DataRow newDataRow = dataTable.NewRow();
                            int columnCount = 0;
                            foreach (Cell currentCell in cells)
                            {
                                value = GetCellValue(currentCell);
                                //There are empty headers which are not added to data table columns. So avoid those.
                                if (columnCount < dataTable.Columns.Count)
                                {
                                    newDataRow[columnCount++] = value;
                                }
                            }
                            dataTable.Rows.Add(newDataRow);
                        }
                    }
                }
            }

Below are the helper methods used
        private static IEnumerable<Cell> GetCellsFromRowIncludingEmptyCells(Row row)
        {
            int currentCount = 0;
            // row is a class level variable representing the current
            foreach (DocumentFormat.OpenXml.Spreadsheet.Cell cell in
                row.Descendants<DocumentFormat.OpenXml.Spreadsheet.Cell>())
            {
                string columnName = GetColumnName(cell.CellReference);
                int currentColumnIndex = ConvertColumnNameToNumber(columnName);
                //Return null for empty cells
                for (; currentCount < currentColumnIndex; currentCount++)
                {
                    yield return null;
                }
                yield return cell;
                currentCount++;
            }
        }

        public static string GetColumnName(string cellReference)
        {
            // Match the column name portion of the cell name.
            Regex regex = new Regex("[A-Za-z]+");
            Match match = regex.Match(cellReference);
 
            return match.Value;
        }

        public static int ConvertColumnNameToNumber(string columnName)
        {
            Regex alpha = new Regex("^[A-Z]+$");
            if (!alpha.IsMatch(columnName)) throw new ArgumentException();
 
            char[] colLetters = columnName.ToCharArray();
            Array.Reverse(colLetters);
 
            int convertedValue = 0;
            for (int i = 0; i < colLetters.Length; i++)
            {
                char letter = colLetters[i];
                int current = i == 0 ? letter - 65 : letter - 64; // ASCII 'A' = 65
                convertedValue += current * (int)Math.Pow(26, i);
            }
 
            return convertedValue;
        }

The only method remaining is GetCellValue(). It can be found in one of my previous post about OpenXML sdk.

Tuesday, October 8, 2013

Reading Excel cell with number formatting using OpenXML sdk

Background

In Excel, we can assign cell styles such as number format, date-time format, etc... If we have an excel document with that formatting, we normally would like to see the formatting when we read the same using a program. But if you are using OpenXML SDK to read excel file, it cannot be achieved directly. We need to read the style index of Excel cell object and find the corresponding CellStyle then format the CellValue based on the format code. Let's see how to achieve that using C# and .Net

Reading excel cell value with formatting

I assume that you have a basic understanding of OpenXML SDK programming. The below steps explains how to read the "A1" cell of an excel document with formatting using open xml sdk.

Step 1 - Obtain the object of Excel cell

First, create a OpenXMLExcelReader class. Accept the excel file name as a parameter via the constructor and keep in a member variable. Then start with the method ReadFirstCell()


    public class OpenXMLExcelReader
    {
        string _filePath;
        public OpenXMLExcelReader(string filePath)
        {
            _filePath = filePath;
        }
        public string ReadFirstCell()
        {
                return ReadCell( "A", 1);
        }
    }


Now, where is the ReadCell method which needs to be a generic implementation which will read any cell value by accepting cell reference? It can be defined as below


        public string ReadCell(string columnName, uint row)
        {
            string value = string.Empty;
            using (SpreadsheetDocument doc = SpreadsheetDocument.Open(_filePath, true))
            {
                var sheet = doc.WorkbookPart.Workbook.GetFirstChild<Sheets>().Elements<Sheet>().First();
                var worksheetPart = (WorksheetPart)doc.WorkbookPart.GetPartById(sheet.Id.Value);
                Cell cell = GetCell(worksheetPart.Worksheet, columnName, row);
                if (cell != null)
                {
                    value = GetCellValue(cell);
                }
            }
            return value;
        }


GetCell() method is returning the cell object nicely. Let's see how the GetCell is implemented. You can see 2 methods which do their responsibilities neatly.


        private static Cell GetCell(Worksheet worksheet, string columnName, uint rowIndex)
        {
            Cell returnCell = null;
            Row row = GetRowFromWorksheet(worksheet, rowIndex);
            if (row != null)
            {
                returnCell= row.Elements<Cell>().Where(c => string.Compare
                       (c.CellReference.Value, columnName +
                       rowIndex, true) == 0).FirstOrDefault();
            }
            return returnCell;
        }
        private static Row GetRowFromWorksheet(Worksheet worksheet, uint rowIndex)
        {
            return worksheet.GetFirstChild<SheetData>().
              Elements<Row>().Where(r => r.RowIndex == rowIndex).FirstOrDefault();
        }

Step 2 - Reading value from excel Cell object using CellStyle

This step is a little more complex. Sometimes we can read InnerText directly. Sometimes we need to get value from a Shared string table. Sometimes using Run elements and if formatting is applied, we need to retrieve the format and apply to the text which is read from cell. Let's see how we can organize it.

        private static string GetCellValue(Cell excelCell)
        {
            string value;
            if (excelCell == null)
                return null;
            if (excelCell.DataType == null)
            {
                return GetCellValueWithoutConsideringDataType(excelCell);
            }
            value = excelCell.InnerText;
            //If none of the below cases are executed, return the innerText            
            switch (excelCell.DataType.Value)
            {
                case CellValues.SharedString:
                    value = GetCellValueByReadingFromSharedString(excelCell);
                    break;
                case CellValues.Boolean:
                    switch (value)
                    {
                        case "0": value = "false"; break;
                        default: value = "true"; break;
                    }
                    break;
            }
            return value;
        }


In most of the cases, if the cell formatting is applied as number the DataType will be null and it will get into the method GetCellValueWithoutConsideringDataType(). Below is the implementation.


        private static string GetCellValueWithoutConsideringDataType(Cell excelCell)
        {
            CellFormat cellFormat = GetCellFormat(excelCell);
            if (cellFormat != null)
            {
                return GetFormatedValue(excelCell, cellFormat);
            }
            else
            {
                return excelCell.InnerText;
            }
        }

If there is a cell format associated with the cell, process accordingly, else return the innerText. Below is the code to obtain CellFormat object from the cell.

        private static CellFormat GetCellFormat(Cell cell)
        {
            WorkbookPart workbookPart = GetWorkbookPartFromCell(cell);
            int styleIndex = (int)cell.StyleIndex.Value;
            CellFormat cellFormat = (CellFormat)workbookPart.WorkbookStylesPart.Stylesheet.CellFormats.ElementAt(styleIndex);
            return cellFormat;
        }
 
        private static WorkbookPart GetWorkbookPartFromCell(Cell cell)
        {
            Worksheet workSheet = cell.Ancestors<Worksheet>().FirstOrDefault();
            SpreadsheetDocument doc = workSheet.WorksheetPart.OpenXmlPackage as SpreadsheetDocument;
            return doc.WorkbookPart;
        }

Now we have cell value and cell format. If the cell format has any number format, lets apply that.

        private static string GetFormatedValue(Cell cell, CellFormat cellformat)
        {
            string value;
            if (cellformat.NumberFormatId != 0)
            {
                string format = GetWorkbookPartFromCell(cell).WorkbookStylesPart.Stylesheet.NumberingFormats.Elements<NumberingFormat>()
                    .Where(i => i.NumberFormatId.Value == cellformat.NumberFormatId.Value)
                    .First().FormatCode;
                double number = double.Parse(cell.InnerText);
                value = number.ToString(format);
            }
            else
            {
                value = cell.InnerText;
            }
            return value;
        }


This handles only Number formatting.If you want to deal with other formats you need to extend this. Reading from the shared string table can be found in my previous post about reading excel cells with formatting.

Tuesday, September 3, 2013

Reading formatted MS Excel cell values using Open XML SDK and showing as HTML

Most of the existing mechanisms which helps to access Excel cells from our applications doesn't give us the formatting of the excel cell. If we select the excel data using OleDB connectors it return plain text. The Excel COM interop give more, but it gives format details for entire cell. What about an Excel cell contains data like below and we want to show the excel cell values with formatting in a MVC application using a Rich Text Editor say KendoUI editor?

Bold data,
Italics, Underlined and big font in green color

Since everything in new Excel file format is XML based and open, the sdk provides the options. But not as easy as we think. We need to get the reference string and we need to iterate through the RunProperties collection. The code is as follows

private string GetCellValue(Cell excelCell)
        {
            if (excelCell == null) 
                return null;
            if (excelCell.DataType == null)
                return excelCell.InnerText;
 
            string value = excelCell.InnerText;
            switch (excelCell.DataType.Value)
            {
                case CellValues.SharedString:
                    value = ReadFromSharedString(excelCell);
                    break;
                case CellValues.Boolean:
                    switch (value)
                    {
                        case "0":
                            value = "false";
                            break;
                        default:
                            value = "true";
                            break;
                    }
                    break;
            }
            return value;
        }

This starts with the assumption that you have basic idea how to obtain Excel Cell object using open xml. If you are not clear on it please refer the link. Make sure you have the open xml sdk dll named DocumentFormat.OpenXml.dll. You may download from this link too.

What is SharedString and ReadFromSharedString? Actually excel keeps a reference to the value and the actual value will be there in a different node. The reference will normally be integer and that will be stored in the excelCell.InnerText property.Lets see the code for ReadSharedString();

private string ReadFromSharedString(Cell cell)
{
    string value = cell.InnerText;
    SharedStringTablePart sstPart = GetSharedTablePart(cell);
    // lookup value in shared string table
    if (sstPart != null && sstPart.SharedStringTable != null)
    {
        int index = int.Parse(value);
        if (sstPart.SharedStringTable.ElementAt(index).ChildElements.Count == 0)
        {
            value = sstPart.SharedStringTable.ElementAt(index).InnerText;
        }
        else
        {
            //ChildElements is collection of Run
            value = GetStringValueFromRuns(sstPart.SharedStringTable.ElementAt(index).ChildElements);
        }
    }
    return value;
}


First part is about how to get the SharedStringTablePart object? Next is about why we are calling GetValueFromRuns(). First things is simple. You can understand by looking the below code. Second one I will explain after the code segment to get the SharedStringTable.


private SharedStringTablePart GetSharedTablePart(Cell cell)
{
    Worksheet workSheet = cell.Ancestors<Worksheet>().FirstOrDefault();
    SpreadsheetDocument doc = workSheet.WorksheetPart.OpenXmlPackage as SpreadsheetDocument;
    SharedStringTablePart sharedStringTablePart = doc.WorkbookPart.GetPartsOfType<SharedStringTablePart>().FirstOrDefault();
    return sharedStringTablePart;
}


Now coming to the GetStringValueFromRuns. Basically the cell data is arranged as series of Run elements. Each run element represents unique formatting and corresponding text.In this case 'Bold Data' will be a run element and 'Italics' will be next run element. So we need to iterate the run collection and create the required formatting.


private string GetStringValueFromRuns(OpenXmlElementList openXmlElementList)
{
    StringBuilder text = new StringBuilder();
    foreach (Run run in openXmlElementList)
    {
        //    //t ADD OPENNING TAGS HERE, if any
        if (run.RunProperties != null)
        {
            foreach (OpenXmlLeafElement element in run.RunProperties.OrderBy(e => e.LocalName))
            {
                //StartTagWrite is the extension method.
                element.StartTagWrite(text);
            }
        }
        text.Append(run.Text.Text.Replace("\n","<br/>"));
        if (run.RunProperties != null)
        {
            foreach (OpenXmlLeafElement element in run.RunProperties.OrderByDescending(e => e.LocalName))
            {
                element.EndTagWrite(text);
            }
        }
    }
    return text.ToString();
}


Each Run will be having Run properties which define the attributes of each run. Important thing to note down is the Run properties classes are different in different Office versions.

Note the extension methods StartTagWrite and EndTagWrite. Those are defined in a different class


    static class Extension
    {
        public static void StartTagWrite(this OpenXmlLeafElement runElement, StringBuilder writer)
        {
            IWriteOperation x = new HTMLWriteOperation { Writer = writer };
            x.StartTagWrite((dynamic)runElement);
        }
        public static void EndTagWrite(this OpenXmlLeafElement runElement, StringBuilder writer)
        {
            IWriteOperation x = new HTMLWriteOperation { Writer = writer };
            x.EndTagWrite((dynamic)runElement);
        }
    }

Here comes a design challenge. Look at the casting using dynamic. This is because each run property is different class. ie there is no base class for run properties. The property class Bold , Italic and Color don't have a common base. The base which we gets is the OpenXmlLeafNode. This is in fact a base class for many nodes other than Run properties. So we need to use the dynamic casting and call the method. Since its dynamic it will call corresponding methods defined in the interface.Below is the interface declaration and corresponding class


private interface IWriteOperation
{
    void StartTagWrite(Bold bold);
    void StartTagWrite(Italic it);
    void StartTagWrite(Underline underline);
    void StartTagWrite(Color c);
    void StartTagWrite(Font font);
    void StartTagWrite(FontSize fontSize);
    void StartTagWrite(FontFamily fontFamily);
    void StartTagWrite(FontScheme fontScheme);
    void StartTagWrite(RunFont runFont);
    void StartTagWrite(Strike strike);
    void StartTagWrite(VerticalTextAlignment vertialAlignment);
    void StartTagWrite(Shadow shadow);
    void StartTagWrite(Outline outline);
    void StartTagWrite(Condense condense);

    void EndTagWrite(Bold b);
    void EndTagWrite(Italic b);
    void EndTagWrite(Underline b);
    void EndTagWrite(Color u);
    void EndTagWrite(Font u);
    void EndTagWrite(FontSize u);
    void EndTagWrite(FontFamily u);
    void EndTagWrite(RunFont u);
    void EndTagWrite(FontScheme u);
    void EndTagWrite(Strike u);
    void EndTagWrite(VerticalTextAlignment u);
    void EndTagWrite(Shadow u);
    void EndTagWrite(Outline u);
    void EndTagWrite(Condense u);
}
private class HTMLWriteOperation : IWriteOperation
{
    public StringBuilder Writer { get; set; }

    void IWriteOperation.StartTagWrite(Bold iThing) { Writer.AppendLine("<B>"); }
    void IWriteOperation.EndTagWrite(Bold iThing) { Writer.AppendLine("</B>"); }

    void IWriteOperation.EndTagWrite(Underline aThing) { Writer.AppendLine("</U>"); }
    void IWriteOperation.StartTagWrite(Underline aThing) { Writer.AppendLine("<U>"); }

    void IWriteOperation.StartTagWrite(Italic aThing) { Writer.AppendFormat("<I>"); }
    void IWriteOperation.EndTagWrite(Italic aThing) { Writer.AppendFormat("</I>"); }

    void IWriteOperation.StartTagWrite(Strike u) { Writer.AppendLine("<del>"); }
    void IWriteOperation.EndTagWrite(Strike aThing) { Writer.AppendLine("</del>"); }

    void IWriteOperation.StartTagWrite(Color u)
    {
        if (u.Rgb != null)
        {
            string colorFormat = @"<span style=""color:#{0};"">";
            string span = string.Format(colorFormat, u.Rgb.Value.Substring(2, 6));
            Writer.AppendLine(span);
        }
    }
    void IWriteOperation.EndTagWrite(Color aThing)
    {
        Writer.AppendLine("</span>");
    }
    void IWriteOperation.StartTagWrite(RunFont u)
    {
        if (u.Val.HasValue)
        {
            string fontFormat = @"<span style=""font-family:'{0}';"">";
            string span = string.Format(fontFormat, u.Val.Value);
            Writer.AppendLine(span);
        }
    }
    void IWriteOperation.EndTagWrite(RunFont aThing)
    {
        Writer.AppendLine("</span>");
    }

    void IWriteOperation.EndTagWrite(FontSize aThing)
    {
        Writer.AppendLine("</span>");
    }
    void IWriteOperation.StartTagWrite(FontSize u)
    {
        string fontSizeFormat = @"<span style=""font-size:{0}px;"">";
        string span = string.Format(fontSizeFormat, u.Val);
        Writer.AppendLine(span);
    }

    void IWriteOperation.StartTagWrite(Font u) { }
    void IWriteOperation.EndTagWrite(Font aThing) { }

    void IWriteOperation.EndTagWrite(FontScheme aThing) { }
    void IWriteOperation.StartTagWrite(FontScheme u) { }

    void IWriteOperation.EndTagWrite(Condense aThing) { }
    void IWriteOperation.StartTagWrite(Condense u) { }
    
    void IWriteOperation.EndTagWrite(VerticalTextAlignment aThing) { }
    void IWriteOperation.StartTagWrite(VerticalTextAlignment u) { }

    void IWriteOperation.EndTagWrite(Shadow aThing) { }
    void IWriteOperation.StartTagWrite(Shadow u) { }

    void IWriteOperation.StartTagWrite(FontFamily u) { }
    void IWriteOperation.EndTagWrite(FontFamily aThing) { }

    void IWriteOperation.StartTagWrite(Outline u) { }
    void IWriteOperation.EndTagWrite(Outline aThing) { }   
}

Reading a cell using OpenXML itself involves lot of code. So this is certainly not going to be easy to understand. Let me know if anybody needs a sample which does it.