Click here to Skip to main content
15,881,027 members
Articles / Productivity Apps and Services / Microsoft Office
Tip/Trick

Read and Write Excel File Dynamically

Rate me:
Please Sign up or sign in to vote.
5.00/5 (11 votes)
7 Jul 2013CPOL2 min read 57.2K   3.8K   35   6
This tip describes how to read Excel files and make an array of objects from Excel.

Introduction

This tip discusses reading and writing Excel files dynamically. This tip can help you extract Excel data and make a list of objects that is generated for that Excel file.

Background

At first, I wrote this library for report result, but now I use it more for converting Excel to JSON!

Using the Code

In this tip, I decided to describe two parts, one part related to how I can read Excel file and the second part describes how I can generate a class dynamically and fill it.

When an Excel file is passed to the code, the first row of Excel file chooses as a class properties that we want to generate it. This functionality is implemented in GetRowValues static method in Wisgance.Office.Excel.Reader.Read class:

C#
private static List<string> GetColumnValues(Stream file, string sheetName, string reference)
       {
           var result = new List<string>();

           //Read Excel File by OpenXml Library
           using (var document = SpreadsheetDocument.Open(file, false))
           {
               var workbook = document.WorkbookPart;

               var theSheet = workbook.Workbook.Descendants<Sheet>().FirstOrDefault(s => s.Name == sheetName) ??
                                workbook.Workbook.Descendants<Sheet>().FirstOrDefault(sheet => true);

               var worksheet = (WorksheetPart)(workbook.GetPartById(theSheet.Id));

               var cells = worksheet.Worksheet.Descendants<Cell>().Where(c => GetCellCol(c.CellReference).ToUpper() == reference);

               //get cell data by calling ExtractCellValue function
               result.AddRange(from theCell in cells where theCell != null select ExtractCellValue(theCell, workbook));
           }

           return result;
       }

In this function and some others like GetRowValues or GetCellData exists argument named references. This argument gets Excel cell address, for example for first row data, we send "1" but for first column, we send "A".

After extracting first row data, we passed these data to the CreateNewObject function in Wisgance.Reflection.WisganceTypeGenerator class.

C#
public static object CreateNewObject(List<FieldMask> props)
      {
          var myType = CompileResultType(props);
          var myObject = Activator.CreateInstance(myType);
          return myObject;
      }

In the first line, we generate a type via extracted data from Excel (CompileResultType) . In the second line, we create an instance of this class and return it.

C#
while (true)
            {
                var obj = WisganceTypeGenerator.CreateNewObject(objProp);
                var values = GetRowValues(stream, "", (k + 1).ToString());
                if (!values.Any())
                    break;
                for (var c = 0; c < objProp.Count; c++)
                {
                    try
                    {
                        var propertyInfo = obj.GetType().GetProperty(objProp[c].FieldName);
                        propertyInfo.SetValue(obj, values[c], null);
                    }
                    catch (Exception) { }
                }
                result.Add(obj);
                k++;
            } 

While true loop, this part is for reading data till it reaches the empty row. In each iteration, an object instantiates and fills properties value by selected row cell values.

For writing a list of objects in Excel, call Do function in Wisgance.Office.Excel.Writer.Write.

C#
if (headerNames == null)
{
	headerNames = new ExcelHeaderList();
	foreach (var o in ObjUtility.GetPropertyInfo(objects[0]))
    	{
       		headerNames.Add(o, o);
      	}
} 

If headerNames is null, automatically set the property name as an Excel header, and also you can pass headerList if you want to customize the header name.

You can download it in Nuget here or see the source in GitHub here.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Iran (Islamic Republic of) Iran (Islamic Republic of)
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionRead File Excel When not exists Data in the First Row or Column ! Pin
Member 1078077728-Oct-16 9:15
Member 1078077728-Oct-16 9:15 
GeneralMy vote of 2 Pin
Arslan Elahi26-Feb-14 1:52
professionalArslan Elahi26-Feb-14 1:52 
GeneralRe: My vote of 2 Pin
Behrooz Bahrameh9-Apr-14 9:34
Behrooz Bahrameh9-Apr-14 9:34 
GeneralMy vote of 5 Pin
Amir Mohammad Nasrollahi27-Jul-13 22:14
professionalAmir Mohammad Nasrollahi27-Jul-13 22:14 
GeneralMy vote of 5 Pin
M.Kouchi9-Jul-13 0:55
M.Kouchi9-Jul-13 0:55 
GeneralMy vote of 5 Pin
Afshin Mehrabani8-Jul-13 20:03
Afshin Mehrabani8-Jul-13 20:03 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.