c Example of using excel files for reading and writing

  • 2020-06-12 10:30:47
  • OfStack

Since csv is supported, one block is written
Workbook,Worksheet using Aspose.Cells(party 3)

To read Excel into the list of property objects, you need to pass in the object type and file path.
Ex. :
List < PropSetCurrency > currencyList = this.GetObjectList < PropSetCurrency > (filePath);
Note: The Excel header needs to correspond to the object name (unordered) and column 1 cannot be empty


To save the property object list to Excel, you need to pass in the object list and the full path to the saved file.
Ex. :
this.SetExcelList(currencyList,"c://currencyList.excel");



/// <summary>
///  from Excel To get the data 
/// </summary>
/// <typeparam name="T"> object </typeparam>
/// <param name="filePath"> File full path </param>
/// <returns> The object list </returns>
public List<T> GetObjectList<T>(string filePath) where T : new()
{
    List<T> list = new List<T>();
    if (!filePath.Trim().EndsWith("csv") && !filePath.Trim().EndsWith("xlsx"))
    {
return list;
    }
    Type type = typeof(T);
    Workbook workbook = new Workbook(filePath);
    Worksheet sheet = workbook.Worksheets[0];
    //  Get the title list 
    var titleDic = this.GetTitleDic(sheet);
    //  Loop through each row of data 
    for (int i = 1; i < int.MaxValue; i++)
    {
//  The action ends when empty 
if (string.IsNullOrEmpty(sheet.Cells[i, 0].StringValue))
{
    break;
}
T instance = new T();
//  Loop assigns each property 
foreach (var item in type.GetProperties())
{
    if (titleDic.ContainsKey(item.Name))
    {
string str = sheet.Cells[i, titleDic[item.Name]].StringValue;
if (!string.IsNullOrEmpty(str))
{
    try
    {
//  Conversion assignments are made according to type 
if (item.PropertyType == typeof(string))
{
    item.SetValue(instance, str);
}
else if (item.PropertyType.IsEnum)
{
    item.SetValue(instance, int.Parse(str));
}
else
{
    MethodInfo method = item.PropertyType.GetMethod("Parse", new Type[] { typeof(string) });
    object obj = null;
    if (method != null)
    {
obj = method.Invoke(null, new object[] { str });
item.SetValue(instance, obj);
    }
}
    }
    catch (Exception)
    {
//  Get error 
    }
}
    }
}
list.Add(instance);
    }
    return list;
}
/// <summary>
///  The object List Save to Excel
/// </summary>
/// <typeparam name="T"> object </typeparam>
/// <param name="objList"> The object list </param>
/// <param name="saveFilePath"> Save the full path to the file , Including file types </param>
public void SetExcelList<T>(List<T> objList, string saveFilePath)
{
    if (!saveFilePath.Trim().EndsWith("csv") && !saveFilePath.Trim().EndsWith("xlsx"))
    {
return;
    }
    Workbook workbook = new Workbook();
    Worksheet sheet = workbook.Worksheets[0];
    //  Freeze the first 1 line 
    sheet.FreezePanes(1, 1, 1, 0);
    //  The loop inserts each row 
    int row = 0;
    foreach (var obj in objList)
    {
int column = 0;
var properties = obj.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.DeclaredOnly);
if (row == 0)
{
    foreach (var titName in properties)
    {
sheet.Cells[0, column].PutValue(titName.Name);
column++;
    }
    row++;
}
//  The loop inserts each column of the current row 
column = 0;
foreach (var property in properties)
{
    var itemValue = property.GetValue(obj);
    sheet.Cells[row, column].PutValue(itemValue.ToString());
    column++;
}
row++;
    }
    workbook.Save(saveFilePath);
}
/// <summary>
///  Gets the header row data 
/// </summary>
/// <param name="sheet">sheet</param>
/// <returns> Header line data </returns>
private Dictionary<string, int> GetTitleDic(Worksheet sheet)
{
    Dictionary<string, int> titList = new Dictionary<string, int>();
    for (int i = 0; i < int.MaxValue; i++)
    {
if (sheet.Cells[0, i].StringValue == string.Empty)
{
    return titList;
}
titList.Add(sheet.Cells[0, i].StringValue, i);
    }
    return titList;
}


Related articles: