SoFunction
Updated on 2025-03-07

C# Read and write Excel file usage example


/// <summary>
/// Get data from Excel
/// </summary>
/// <typeparam name="T">Object</typeparam>
/// <param name="filePath">Full path of file</param>
/// <returns>Object List</returns>
public List<T> GetObjectList<T>(string filePath) where T : new()
{
    List<T> list = new List<T>();
    if (!().EndsWith("csv") && !().EndsWith("xlsx"))
    {
return list;
    }

    Type type = typeof(T);
    Workbook workbook = new Workbook(filePath);
    Worksheet sheet = [0];

// Get the title list
    var titleDic = (sheet);

// Loop each row of data
    for (int i = 1; i < ; i++)
    {
// End when the behavior is empty
if (([i, 0].StringValue))
{
    break;
}

T instance = new T();

// Loop to assign each attribute
foreach (var item in ())
{
    if (())
    {
string str = [i, titleDic[]].StringValue;
if (!(str))
{
    try
    {
// Convert value according to type
if ( == typeof(string))
{
    (instance, str);
}
else if ()
{
    (instance, (str));
}
else
{
    MethodInfo method = ("Parse", new Type[] { typeof(string) });
    object obj = null;
    if (method != null)
    {
obj = (null, new object[] { str });
(instance, obj);
    }
}
    }
    catch (Exception)
    {
// Get error
    }
}
    }
}

(instance);
    }

    return list;
}

/// <summary>
/// Save object List to Excel
/// </summary>
/// <typeparam name="T">Object</typeparam>
/// <param name="objList">Object List</param>
/// <param name="saveFilePath">The complete path to save the file, including file type</param>
public void SetExcelList<T>(List<T> objList, string saveFilePath)
{
    if (!().EndsWith("csv") && !().EndsWith("xlsx"))
    {
return;
    }

    Workbook workbook = new Workbook();
    Worksheet sheet = [0];

// Freeze the first line
    (1, 1, 1, 0);

// Loop into each row
    int row = 0;
    foreach (var obj in objList)
    {
int column = 0;
var properties = ().GetProperties( | | | );
if (row == 0)
{
    foreach (var titName in properties)
    {
[0, column].PutValue();
column++;
    }

    row++;
}

// Loop into each column of the current row
column = 0;
foreach (var property in properties)
{
    var itemValue = (obj);
    [row, column].PutValue(());
    column++;
}

row++;
    }

    (saveFilePath);
}

/// <summary>
/// Get the title line data
/// </summary>
/// <param name="sheet">sheet</param>
/// <returns>Title line data</returns>
private Dictionary<string, int> GetTitleDic(Worksheet sheet)
{
    Dictionary<string, int> titList = new Dictionary<string, int>();
    for (int i = 0; i < ; i++)
    {
if ([0, i].StringValue == )
{
    return titList;
}

([0, i].StringValue, i);
    }

    return titList;
}