npoi+ reflection + Custom features upload Excel to list and verify

Source: Internet
Author: User

1. Custom Features

[AttributeUsage (attributetargets.property, AllowMultiple =false, inherited =true)]     Public classPropertydescriptionattribute:attribute {Private BOOL_allownullorempty =true;  PublicPropertydescriptionattribute () {}/// <summary>        ///whether to allow null or null values/// </summary>         Public BOOLAllownullorempty {Get            {                return  This. _allownullorempty; }            Set            {                 This. _allownullorempty =value; }        }    }

2. Defining a class (assuming user information)

 Public class Uploadusermodel    {        false)]          Public string Get Set ; }         false )]        publicstringgetset;}    

Custom-specific to identify these two messages cannot be empty

3. Implement

/// <summary>///property_name Array: Value corresponds to Excel column one by one/// </summary>Private ReadOnly string[] Property_name = {"Name","Phone" };PrivateList<uploadusermodel>exceltolist (Httppostedfile excelfile) {Iworkbook workbook=NULL; Isheet sheet=NULL; intColCount =0; List<UploadUserModel> users =NewList<uploadusermodel>(); if(ExcelFile.FileName.IndexOf (". xlsx") >0) {Workbook=NewXssfworkbook (Excelfile.inputstream); }            Else if(ExcelFile.FileName.IndexOf (". xls") >0) {Workbook=NewHssfworkbook (Excelfile.inputstream); }            if(Workbook! =NULL) {Sheet= Workbook. Getsheetat (0); if(Sheet! =NULL&& sheet. Lastrownum >0) {ColCount= Sheet. GetRow (0). Lastcellnum;//get number of columns//start parsing from the second line                     for(intRowIndex =1; RowIndex <= Sheet. Lastrownum; rowindex++)                    {                        varCurrow = sheet. GetRow (RowIndex);//gets the current rowUploadusermodel user =NewUploadusermodel (); Type CType=user.                        GetType (); //Parse Columns                         for(intColindex =0; Colindex < ColCount; colindex++)                        {                            varCurcell =Currow.getcell (Colindex); if(Curcell! =NULL) {curcell.setcelltype (celltype.string);//set the cell to string type, uniform value method                            }                            //define property_name to avoid if judgmentPropertyInfo PropertyInfo =Ctype.getproperty (Property_name[colindex]); //Get custom Attributes                            Object[] Customattrs = Propertyinfo.getcustomattributes (typeof(Propertydescriptionattribute),true); if(Customattrs.length >0) {Propertydescriptionattribute attr= customattrs[0] asPropertydescriptionattribute; if(!attr. Allownullorempty)//property value cannot be empty                                {                                    if(Curcell = =NULL)                                    {                                        Throw NewException ("Section"+ (RowIndex +1). ToString () +"the line has not been filled in, please fill in and re-upload. "); }                                    Else if(string. IsNullOrEmpty (Curcell.stringcellvalue)) {Throw NewException ("Section"+ (RowIndex +1). ToString () +"the line has not been filled in, please fill in and re-upload. "); }                                }                                ObjectCellvalue =NULL; if(Curcell = =NULL) {Cellvalue=""; }                                Else{Cellvalue=Curcell.stringcellvalue; }                                if(!propertyInfo.PropertyType.IsGenericType) {//Non-genericPropertyinfo.setvalue (user, Curcell = =NULL?NULL: Convert.changetype (Cellvalue, Propertyinfo.propertytype),NULL); }                                Else                                {                                    //Generic nullable<>Type generictypedefinition =propertyInfo.PropertyType.GetGenericTypeDefinition (); if(Generictypedefinition = =typeof(nullable<>) {propertyinfo.setvalue (user, Curcell ==NULL?NULL: Convert.changetype (Cellvalue, Nullable.getunderlyingtype (Propertyinfo.propertytype)),NULL);                        }                                }                            }                                                    } Users.                    ADD (user); }                }            }            Else            {                Throw NewException ("Excel parsing exceptions"); }            foreach(varIteminchusers) {                if(!Checkphonegs (item. Phone)) {Throw NewException ("The phone number format is incorrect:"+item.                Phone); }            }            returnusers; }

Don't look at the trouble, the core code is simple. Using reflection and defining property_name arrays is for code reuse. The last generic, non-generic judgment can be deleted, and it is estimated that it is generally less than

npoi+ reflection + Custom features upload Excel to list and verify

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.