none
Open Xml RRS feed

  • Question

  • I am trying to find the access to the table header of all the tables in the excel file using openxml library
    Wednesday, August 3, 2016 9:41 AM

Answers

  • Hi,

    Try the following code.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using DocumentFormat.OpenXml.Packaging;
    using DocumentFormat.OpenXml.Spreadsheet;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                string fileName = (@"C:\Users\Administrator\Desktop\ttt.xlsx");
                var items = GetTableHeader(fileName, "Sheet1");
                string line = string.Join(",", items.ToArray());
                Console.WriteLine(line);
                Console.ReadKey();
            }
    
            public static List<string>GetTableHeader(string FileName,string worksheetName)
            {
                List<string> items = new List<string>();
                using (SpreadsheetDocument document = SpreadsheetDocument.Open(FileName, true))
                {
    
                    IEnumerable<Sheet> sheets = document.WorkbookPart.Workbook.Descendants<Sheet>().Where(s => s.Name == worksheetName);
                    if (sheets.Count() == 0)
                    {
                        return null;
                    }
    
                    WorksheetPart worksheetPart = (WorksheetPart)document.WorkbookPart.GetPartById(sheets.First().Id);
                 
                    //get all the tables
                    foreach (TableDefinitionPart tablesPart in worksheetPart.TableDefinitionParts)
                    {
                         
                        Table table = tablesPart.Table;
                        // get  all the table columns
                        foreach (TableColumn tableColunm in tablesPart.Table.TableColumns)
                        {
                            items.Add(tableColunm.Name.Value);
                        }
                    }
                    return items;
                }
            }
        }
    }
    

    Thursday, August 4, 2016 5:14 AM
    Moderator