C# Excel导入导出

时间:2022-01-01 07:52:41

/// 实体类集合导出到Excle2003

/// </summary>

/// <param>单元头的Key和Value:{ { "UserName", "姓名" }, { "Age", "年龄" } };</param>

/// <param>数据源</param>

/// <param>工作表名称</param>

/// <returns>文件的下载地址</returns>

public static string EntityListToExcel2003(Dictionary<string, string> cellHeard, IList enList, string sheetName)

{

    try

    {

        string fileName = sheetName + "-" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".xls"; // 文件名称

        string urlPath = "UpFiles/ExcelFiles/" + fileName; // 文件下载的URL地址,,供给前台下载

        string filePath = HttpContext.Current.Server.MapPath("\\" + urlPath); // 文件路径

 

        // 1.检测是否存在文件夹,若不存在就建立个文件夹

        string directoryName = Path.GetDirectoryName(filePath);

        if (!Directory.Exists(directoryName))

        {

            Directory.CreateDirectory(directoryName);

        }

 

        // 2.解析单元格头部,设置单元头的中文名称

        HSSFWorkbook workbook = new HSSFWorkbook(); // 工作簿

        ISheet sheet = workbook.CreateSheet(sheetName); // 工作表

        IRow row = sheet.CreateRow(0);

        List<string> keys = cellHeard.Keys.ToList();

        for (int i = 0; i < keys.Count; i++)

        {

            row.CreateCell(i).SetCellValue(cellHeard[keys[i]]); // 列名为Key的值

        }

 

        // 3.List对象的值赋值到Excel的单元格里

        int rowIndex = 1; // 从第二行开始赋值(第一行已设置为单元头)

        foreach (var en in enList)

        {

            IRow rowTmp = sheet.CreateRow(rowIndex);

            for (int i = 0; i < keys.Count; i++) // 根据指定的属性名称,获取对象指定属性的值

            {

                string cellValue = ""; // 单元格的值

                object properotyValue = null; // 属性的值

                System.Reflection.PropertyInfo properotyInfo = null; // 属性的信息

 

                // 3.1 若属性头的名称包含‘.‘,就表示是子类里的属性,那么就要遍历子类,eg:UserEn.UserName

                if (keys[i].IndexOf(".") >= 0)

                {

                    // 3.1.1 解析子类属性(这里只解析1层子类,多层子类未处理)

                    string[] properotyArray = keys[i].Split(new string[] { "." }, StringSplitOptions.RemoveEmptyEntries);

                    string subClassName = properotyArray[0]; // ‘.‘前面的为子类的名称

                    string subClassProperotyName = properotyArray[1]; // ‘.‘后面的为子类的属性名称

                    System.Reflection.PropertyInfo subClassInfo = en.GetType().GetProperty(subClassName); // 获取子类的类型

                    if (subClassInfo != null)

                    {

                        // 3.1.2 获取子类的实例