C# programming Excel import and export (source code download) (Part 1)

黄舟
Release: 2017-02-06 16:38:33
Original
2399 people have browsed it

This article mainly introduces Excel import and export in C#.

1. Introduction


1.1 Third-party class library: NPOI

Description: NPOI is the .NET version of the POI project, which can be used Reading and writing operations of Excel and Word.

Advantages: No need to install Office environment.

Download address: http://npoi.codeplex.com/releases

1.2 Introduction to Excel structure

Workbook: Each Excel file can be understood as one work log.

Worksheet (Sheet): A workbook (Workbook) can contain multiple worksheets.

Row: A worksheet (Sheet) can contain multiple rows.

C# programming Excel import and export (source code download) (Part 1)

2. Excel import


2.1 Operation process

C# programming Excel import and export (source code download) (Part 1)

2.2 NPOI operation code


##Instructions: Convert Excel file to List

Steps:

①Read Excel file and initialize a workbook (Workbook);

② Get a worksheet (Sheet) from the workbook; the default is the first worksheet of the workbook;

③ Traverse All rows (rows) of the worksheet; by default, the traversal starts from the second row, and the first row (serial number 0) is the cell header;

④Traverse each cell (cell) of the row, according to a certain The rules assign values ​​to the properties of objects.

Code:

/// 从Excel2003取数据并记录到List集合里
/// <param name="cellHeard">单元头的Key和Value:{ { "UserName", "姓名" }, { "Age", "年龄" } };</param>
/// <param name="filePath">保存文件绝对路径</param>
/// <param name="errorMsg">错误信息</param>
/// <returns>转换好的List对象集合</returns>
private static List<T> Excel2003ToEntityList<T>(Dictionary<string, string> cellHeard, string filePath, out StringBuilder errorMsg) where T : new()
{
    errorMsg = new StringBuilder(); // 错误信息,Excel转换到实体对象时,会有格式的错误信息
    List<T> enlist = new List<T>(); // 转换后的集合
    List<string> keys = cellHeard.Keys.ToList(); // 要赋值的实体对象属性名称
    try
    {
        using (FileStream fs = File.OpenRead(filePath))
        {
            HSSFWorkbook workbook = new HSSFWorkbook(fs);
            HSSFSheet sheet = (HSSFSheet)workbook.GetSheetAt(0); // 获取此文件第一个Sheet页
            for (int i = 1; i <= sheet.LastRowNum; i++) // 从1开始,第0行为单元头
            {
                // 1.判断当前行是否空行,若空行就不在进行读取下一行操作,结束Excel读取操作
                if (sheet.GetRow(i) == null)
                {
                    break;
                }
                T en = new T();
                string errStr = ""; // 当前行转换时,是否有错误信息,格式为:第1行数据转换异常:XXX列;
                for (int j = 0; j < keys.Count; j++)
                {
                    // 2.若属性头的名称包含&#39;.&#39;,就表示是子类里的属性,那么就要遍历子类,eg:UserEn.TrueName
                    if (keys[j].IndexOf(".") >= 0)
                    {
                        // 2.1解析子类属性
                        string[] properotyArray = keys[j].Split(new string[] { "." }, StringSplitOptions.RemoveEmptyEntries);
                        string subClassName = properotyArray[0]; // &#39;.&#39;前面的为子类的名称
                        string subClassProperotyName = properotyArray[1]; // &#39;.&#39;后面的为子类的属性名称
                        System.Reflection.PropertyInfo subClassInfo = en.GetType().GetProperty(subClassName); // 获取子类的类型
                        if (subClassInfo != null)
                        {
                            // 2.1.1 获取子类的实例
                            var subClassEn = en.GetType().GetProperty(subClassName).GetValue(en, null);
                            // 2.1.2 根据属性名称获取子类里的属性信息
                            System.Reflection.PropertyInfo properotyInfo = subClassInfo.PropertyType.GetProperty(subClassProperotyName);
                            if (properotyInfo != null)
                            {
                                try
                                {
                                    // Excel单元格的值转换为对象属性的值,若类型不对,记录出错信息
                                    properotyInfo.SetValue(subClassEn, GetExcelCellToProperty(properotyInfo.PropertyType, sheet.GetRow(i).GetCell(j)), null);
                                }
                                catch (Exception e)
                                {
                                    if (errStr.Length == 0)
                                    {
                                        errStr = "第" + i + "行数据转换异常:";
                                    }
                                    errStr += cellHeard[keys[j]] + "列;";
                                }
                            }
                        }
                    }
                    else
                    {
                        // 3.给指定的属性赋值
                        System.Reflection.PropertyInfo properotyInfo = en.GetType().GetProperty(keys[j]);
                        if (properotyInfo != null)
                        {
                            try
                            {
                                // Excel单元格的值转换为对象属性的值,若类型不对,记录出错信息
                                properotyInfo.SetValue(en, GetExcelCellToProperty(properotyInfo.PropertyType, sheet.GetRow(i).GetCell(j)), null);
                            }
                            catch (Exception e)
                            {
                                if (errStr.Length == 0)
                                {
                                    errStr = "第" + i + "行数据转换异常:";
                                }
                                errStr += cellHeard[keys[j]] + "列;";
                            }
                        }
                    }
                }
                // 若有错误信息,就添加到错误信息里
                if (errStr.Length > 0)
                {
                    errorMsg.AppendLine(errStr);
                }
                enlist.Add(en);
            }
        }
        return enlist;
    }
    catch (Exception ex)
    {
        throw ex;
    }
}
Copy after login

2.3 C# logical operation code

Description: Perform subsequent operations on the Excel-converted List; such as: detect validity, persistent storage Wait

Steps:

①Call the 2.2 code to convert the Excel file to List.

② Check the validity of List: whether the required items are empty, whether there are duplicate records, etc.

③Perform persistent storage operation on List. Such as: stored in the database.

④返回操作结果。

代码:

public void ImportExcel(HttpContext context)
{
    StringBuilder errorMsg = new StringBuilder(); // 错误信息
    try
    {
        #region 1.获取Excel文件并转换为一个List集合
        // 1.1存放Excel文件到本地服务器
        HttpPostedFile filePost = context.Request.Files["filed"]; // 获取上传的文件
        string filePath = ExcelHelper.SaveExcelFile(filePost); // 保存文件并获取文件路径
 
        // 单元格抬头
        // key:实体对象属性名称,可通过反射获取值
        // value:属性对应的中文注解
        Dictionary<string, string> cellheader = new Dictionary<string, string> {
            { "Name", "姓名" },
            { "Age", "年龄" },
            { "GenderName", "性别" },
            { "TranscriptsEn.ChineseScores", "语文成绩" },
            { "TranscriptsEn.MathScores", "数学成绩" },
        };
 
        // 1.2解析文件,存放到一个List集合里
        List<UserEntity> enlist = ExcelHelper.ExcelToEntityList<UserEntity>(cellheader, filePath, out errorMsg);
 
        #endregion
 
        #region 2.对List集合进行有效性校验
 
        #region 2.1检测必填项是否必填
 
        for (int i = 0; i < enlist.Count; i++)
        {
            UserEntity en = enlist[i];
            string errorMsgStr = "第" + (i + 1) + "行数据检测异常:";
            bool isHaveNoInputValue = false; // 是否含有未输入项
            if (string.IsNullOrEmpty(en.Name))
            {
                errorMsgStr += "姓名列不能为空;";
                isHaveNoInputValue = true;
            }
            if (isHaveNoInputValue) // 若必填项有值未填
            {
                en.IsExcelVaildateOK = false;
                errorMsg.AppendLine(errorMsgStr);
            }
        }
 
        #endregion
 
        #region 2.2检测Excel中是否有重复对象
 
        for (int i = 0; i < enlist.Count; i++)
        {
            UserEntity enA = enlist[i];
            if (enA.IsExcelVaildateOK == false) // 上面验证不通过,不进行此步验证
            {
                continue;
            }
 
            for (int j = i + 1; j < enlist.Count; j++)
            {
                UserEntity enB = enlist[j];
                // 判断必填列是否全部重复
                if (enA.Name == enB.Name)
                {
                    enA.IsExcelVaildateOK = false;
                    enB.IsExcelVaildateOK = false;
                    errorMsg.AppendLine("第" + (i + 1) + "行与第" + (j + 1) + "行的必填列重复了");
                }
            }
        }
 
        #endregion
 
        // TODO:其他检测
 
        #endregion
 
        // 3.TODO:对List集合持久化存储操作。如:存储到数据库
         
        // 4.返回操作结果
        bool isSuccess = false;
        if (errorMsg.Length == 0)
        {
            isSuccess = true; // 若错误信息成都为空,表示无错误信息
        }
        var rs = new { success = isSuccess,  msg = errorMsg.ToString(), data = enlist };
        System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();
        context.Response.ContentType = "text/plain";
        context.Response.Write(js.Serialize(rs)); // 返回Json格式的内容
    }
    catch (Exception ex)
    {
     throw ex;
    }
}
Copy after login

以上就是C#编程之Excel导入、导出(源码下载) (上)的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!