Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EPPlus Reading Column Headers

Tags:

c#

Is there an easy way to tell EPPlus that a row is a header? Or should I create the headers by specifying a range using SelectedRange, remove it from the sheet and iterate the cells that remain?

I ended up doing this:

class Program
{
    static void Main(string[] args)
    {
        DirectoryInfo outputDir = new DirectoryInfo(@"C:\testdump\excelimports");
        FileInfo existingFile = new FileInfo(outputDir.FullName + @"\Stormers.xlsx");
        Dictionary<string, string> arrColumnNames = new Dictionary<string,string>() { { "First Name", "" }, { "Last Name", "" }, { "Email Address", "" } };
        using (ExcelPackage package = new ExcelPackage(existingFile))
        {
            ExcelWorksheet sheet = package.Workbook.Worksheets[1];
            var q = from cell in sheet.Cells
                    where arrColumnNames.ContainsKey(cell.Value.ToString())
                    select cell;

            foreach (var c in q)
            {
                arrColumnNames[c.Value.ToString()] = c.Address;
            }
            foreach (var ck in arrColumnNames)
            {
                Console.WriteLine("{0} - {1}", ck.Key, ck.Value);
            }

            var qValues = from r in sheet.Cells
                          where !arrColumnNames.ContainsValue(r.Address.ToString())
                          select r;

            foreach (var r in qValues)
            {
                Console.WriteLine("{0} - {1}", r.Address, r.Value);
            }
        }
    }
}
like image 225
fr3dr1k8009 Avatar asked Apr 23 '12 09:04

fr3dr1k8009


People also ask

Does EPPlus require Excel?

No, it does not require Excel to be installed on the server, as you can read in the docs: EPPlus is a . NET library that reads and writes Excel files using the Office Open XML format (xlsx).

What is EPPlus DLL?

EPPlus is a very helpful open-source 3rd party DLL for writing data to excel. EPPlus supports multiple properties of spreadsheets like cell ranges, cell styling, charts, pictures, shapes, comments, tables, protection, encryption, pivot tables, data validation, conditional formatting, formula calculation, etc.


2 Answers

I needed to enumerate through header and display all the columns headers to my end user. I took Muhammad Mubashir code as base and changed/converted it to extension method and removed hard-coded numbers from it.

public static class ExcelWorksheetExtension
{
    public static string[] GetHeaderColumns(this ExcelWorksheet sheet)
    {
        List<string> columnNames = new List<string>();
        foreach (var firstRowCell in sheet.Cells[sheet.Dimension.Start.Row, sheet.Dimension.Start.Column, 1, sheet.Dimension.End.Column]) 
            columnNames.Add(firstRowCell.Text);
        return columnNames.ToArray();
    }
}
like image 187
ndd Avatar answered Oct 01 '22 16:10

ndd


var pck = new OfficeOpenXml.ExcelPackage();
pck.Load(new System.IO.FileInfo(path).OpenRead());
var ws = pck.Workbook.Worksheets["Worksheet1"];
DataTable tbl = new DataTable();
var hasHeader = true;
foreach (var firstRowCell in ws.Cells[1, 1, 1, ws.Dimension.End.Column]){
      tbl.Columns.Add(hasHeader ? firstRowCell.Text : string.Format("Column {0}", firstRowCell.Start.Column));
}
var startRow = hasHeader ? 2 : 1;
for (var rowNum = startRow; rowNum <= ws.Dimension.End.Row; rowNum++){
     var wsRow = ws.Cells[rowNum, 1, rowNum, ws.Dimension.End.Column];
     var row = tbl.NewRow();
     foreach (var cell in wsRow){
           row[cell.Start.Column - 1] = cell.Text;
     }
     tbl.Rows.Add(row);
}
like image 45
Muhammad Mubashir Avatar answered Oct 01 '22 16:10

Muhammad Mubashir