skayred
skayred

Reputation: 10713

Read first line of XLS without specific sheet name

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?

Upvotes: 0

Views: 2839

Answers (2)

Vincent Tan
Vincent Tan

Reputation: 3166

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.

Upvotes: 0

digaomatias
digaomatias

Reputation: 1194

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);

Upvotes: 3

Related Questions