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++)
            {}

...

2
  • What have you tried so far? Please show code which you have implemented till now. Commented Nov 22, 2019 at 7:10
  • 1
    Edit Done .check my question please Commented Nov 22, 2019 at 7:58

2 Answers 2

2

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

  1. StackOverflow
  2. Microsoft Docs
  3. NuGet
  4. GitHub
Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

It is not really good idea because Interop need installed Office.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.