加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c#读写excel文件使用示例

发布时间:2020-12-15 04:04:21 所属栏目:百科 来源:网络整理
导读:因为支持csv,所以就一块写上了 Workbook,Worksheet using Aspose.Cells(第三方) 把Excel读取到属性对象列表,需要传入对象类型和文件路径. 例: ListPropSetCurrency currencyList = this.GetObjectListPropSetCurrency(filePath); 注:Excel的表头需要和对象名

因为支持csv,所以就一块写上了
Workbook,Worksheet using Aspose.Cells(第三方)

把Excel读取到属性对象列表,需要传入对象类型和文件路径.
例:
List<PropSetCurrency> currencyList = this.GetObjectList<PropSetCurrency>(filePath);
注:Excel的表头需要和对象名对应(可无序),且第一列不能为空


把属性对象列表保存到Excel,需要传入对象列表和保存的文件完整路径.
例:
this.SetExcelList(currencyList,"c://currencyList.excel");


复制代码 代码如下:

/// <summary>
/// 从Excel获取数据
/// </summary>
/// <typeparam name="T">对象</typeparam>
/// <param name="filePath">文件完整路径</param>
/// <returns>对象列表</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];

    // 获取标题列表
    var titleDic = this.GetTitleDic(sheet);

    // 循环每行数据
    for (int i = 1; i < int.MaxValue; i++)
    {
// 行为空时结束
if (string.IsNullOrEmpty(sheet.Cells[i,0].StringValue))
{
    break;
}

T instance = new T();

// 循环赋值每个属性
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
    {
// 根据类型进行转换赋值
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)
    {
// 获取错误
    }
}
    }
}

list.Add(instance);
    }

    return list;
}

/// <summary>
/// 把对象List保存到Excel
/// </summary>
/// <typeparam name="T">对象</typeparam>
/// <param name="objList">对象列表</param>
/// <param name="saveFilePath">保存文件的完整路径,包括文件类型</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];

    // 冻结第一行
    sheet.FreezePanes(1,1,0);

    // 循环插入每行
    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++;
}

// 循环插入当前行的每列
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>
/// 获取标题行数据
/// </summary>
/// <param name="sheet">sheet</param>
/// <returns>标题行数据</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;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读