3

Is there a way to read data from excel and open office spreadsheets and save them to a temporary store, like a DataSet or array? I came across ExcelDataReader (http://exceldatareader.codeplex.com/), but it only works if the user has Excel installed on their computer. Some of our users only have Open Office (and others have neither).

1 Answer 1

2

Here's a simple approach using EPPlus(what i can warmly recommend) that converts it manually to a DataTable:

DataTable tbl = new DataTable();
var pck = new OfficeOpenXml.ExcelPackage();
pck.Load(new System.IO.FileInfo(@"C:\Temp\ExcelFile.xlsx").OpenRead());
if (pck.Workbook.Worksheets.Count != 0)
{
    var sheet = pck.Workbook.Worksheets.First();
    var hasHeader = false; // adjust accordingly '
    foreach (var firstRowCell in sheet.Cells[1, 1, 1, sheet.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 <= sheet.Dimension.End.Row; rowNum++)
    {
        var wsRow = sheet.Cells[rowNum, 1, rowNum, sheet.Dimension.End.Column];
        tbl.Rows.Add(wsRow.Select(cell => cell.Text).ToArray());
    }
}

Originally posted by myself here (VB.NET).

Your Answer

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