0

I've found how to read first line from Excel file with specific sheet name, but in my case I have to read first line of the first sheet.

How can I realize that or I have to use CSV instead of XLS?

skayred
  • 10,603
  • 10
  • 52
  • 94

2 Answers2

3

Did you take a look at the EPPlus library? It makes very easy to work with excel files.

Here is how you would do that using EPPlus:

FileInfo existingFile = new FileInfo("yourfilepathname");

using (var package = new ExcelPackage(existingFile))
{
    ExcelWorkbook workbook = package.Workbook;
    if (workbook != null && workbook.Worksheets.Count > 0)
    {
        //Gets the first worksheet. You can use index also to select your worksheet.
        ExcelWorksheet worksheet = workbook.Worksheets.First();

        int rowIndex = 0;
        int colIndex = 0;        
        //To get the first cell:
        var cellValue = worksheet.Cells[rowIndex, colIndex].Value;


        //YOU CAN ALSO DO A LOOP TO GET ALL VALUES FROM THE FIRST ROW.
    }
}

NPOI is another good option and it can handle XLS files too.

Here's a snippet of NPOI code:

HSSFWorkbook _hssfworkbook = new HSSFWorkbook(OpenFileStream(filePath));
//Getting the sheet
_currentSheet = _hssfworkbook.GetSheetAt(0);
//Getting the row:
_row = CurrentSheet.GetRow(0);
//Getting the cell
_cell = _row.GetCell(0);
digaomatias
  • 1,164
  • 10
  • 21
0

Have you considered SpreadsheetLight? Here's how you do it:

SLDocument sl = new SLDocument("YourExcelFile.xlsx", "TheSheetName");
string FirstLine = sl.GetCellValueAsString("A1");
sl.CloseWithoutSaving();

Disclaimer: I wrote SpreadsheetLight.

Vincent Tan
  • 3,058
  • 22
  • 21