1

I want to read data from column headers of an excel. Each excel file have same header name but header names are in different rows. Please help me out in c# Code. My Code is below.

 var textfile = Request.Files[0];
        string profileimage = Path.GetExtension(textfile.FileName);           
        string ProfileName = path.GetFileNameWithoutExtension(textfile.FileName);
        IExcelDataReader excelReader;     
     excelReader=ExcelReaderFactory.CreateBinaryReader(textfile.InputStream);
         DataSet result = excelReader.AsDataSet();
         DataTable dt = result.Tables[0];
         int Tcount = dt.Rows.Count;
         for (int i = 2; i < dt.Rows.Count; i++)
            {}

...

Dawid Wekwejt
  • 533
  • 1
  • 4
  • 19
Developer
  • 89
  • 1
  • 14

2 Answers2

2

Try to use OpenXML SDK. Here you can find more information about:

  1. StackOverflow
  2. Microsoft Docs
  3. NuGet
  4. GitHub
Dawid Wekwejt
  • 533
  • 1
  • 4
  • 19
1

One way is to use Interop. This comes with office, so you won't need any third party stuff. But be ware that in order TO USE INTEROP YOU NEED OFFICE INSTALLED on the system that runs the application.

using Excel=Microsoft.Office.Interop.Excel; 
// Start Excel.exe
MyApp = new Excel.Application();
// Hide the visual application, you can also choose to omit this to show the excel application while your code works on it.
MyApp.Visible = false;
// Open the file
MyBook = MyApp.Workbooks.Open("Some/Excel/File");
// Get the first sheet
MySheet = MyBook.Sheets[1];
// Get some cell value
MyCell= MySheet.Cells[rowIndex,colIndex]

Then you can itterate over the rows to find the header by either row/column index or string comparison. At last you need to release the COM objects with this (order is important here), or the Excel.exe will keep running:

Marshal.ReleaseComObject(MyCell);
Marshal.ReleaseComObject(MySheet);
Marshal.ReleaseComObject(MyBook);
Marshal.ReleaseComObject(MyApp);

Just make sure to read documentation first, since there are some gotchas when working with interop, like releasing the objects.

Martijn
  • 739
  • 9
  • 26