MVC npoi LINQ export Excel general Class

Source: Internet
Author: User
Tags rowcount

Before writing a model to export the general class of Excel, but in the actual application, may not directly export the model, but through the LINQ query to obtain the final result and then export

General class:

 Public enumDataTypeEnum {Int=0, Float=1, Double=2, String=3, DateTime=4, Date=5    }     Public classExportfieldinfo {/// <summary>        ///field name, for reflection get value/// </summary>         Public stringFieldName {Get;Set; } /// <summary>        ///Chinese name, for export title/// </summary>         Public stringDisplayName {Get;Set; } /// <summary>        ///data types, which are used for casting and formatting, and can actually be obtained by using reflection as a data type, where the display format of date and date is processed/// </summary>         PublicDataTypeEnum DataType {Get;Set; } }     Public classExcelhelper {/// <summary>        ///Export to memory stream/// </summary>        /// <param name= "Data" >list of models that need to be exported</param>        /// <param name= "FieldInfo" >exported Field List information</param>        /// <param name= "Sheetrows" >number of rows per worksheet</param>        /// <returns></returns>         Public StaticMemoryStream Toexcel (list<Object> Data, list<exportfieldinfo> fieldInfo,intSheetrows =65536)        {            //create an object for an Excel fileNpoi. HSSF. Usermodel.hssfworkbook book =NewNpoi. HSSF.            Usermodel.hssfworkbook (); //need to generate work PU Master book            intSheetcount = data. Count/sheetrows +1; intRowCount =data.            Count;  for(inti =0; i < Sheetcount; i++)            {                //Add a sheetNpoi. Ss. Usermodel.isheet sheet = Book. Createsheet ("Sheet"+convert.tostring (i)); //Add the header of the first row to sheetNpoi. Ss. Usermodel.irow rowtitle = sheet. CreateRow (0);  for(intK =0; K < Fieldinfo.count; k++) {Rowtitle.createcell (k). Setcellvalue (Fieldinfo.elementat (k).                DisplayName); }                //an issue where you can only put 65536 lines of records in an Excel workbook//because the head is a row, minus 1.                 for(intj =0; J < Sheetrows-1; J + +)                {                    //progressively writing data to sheet individual rowsNpoi. Ss. Usermodel.irow rowtemp = sheet. CreateRow (j +1); intDataindex = i * (Sheetrows-1) +J;  for(intK =0; K < Fieldinfo.count; k++)                    {                        //Get TypeType type =Data[dataindex].                        GetType (); //gets the property of the specified nameSystem.Reflection.PropertyInfo PropertyInfo =type. GetProperty (Fieldinfo.elementat (k).                        FieldName); //Get Property value                        varValue = Propertyinfo.getvalue (Data[dataindex],NULL); Switch(Fieldinfo.elementat (k). DataType) { CaseDataTypeEnum.Int:rowtemp. Createcell (k).                                Setcellvalue (Convert.ToInt32 (value));  Break;  CaseDataTypeEnum.Float:rowtemp. Createcell (k).                                Setcellvalue (convert.todouble (value));  Break;  CaseDataTypeEnum.Double:rowtemp. Createcell (k).                                Setcellvalue (convert.todouble (value));  Break;  CaseDataTypeEnum.String:rowtemp. Createcell (k).                                Setcellvalue (convert.tostring (value));  Break;  CaseDataTypeEnum.DateTime:rowtemp. Createcell (k). Setcellvalue (Convert.todatetime (value). ToString ("yyyy-mm-dd HH:mm:ss. SSS"));  Break;  CaseDataTypeEnum.Date:rowtemp. Createcell (k). Setcellvalue (Convert.todatetime (value). ToString ("YYYY-MM-DD"));  Break; default:                                 Break; }                    }                    //all record loops complete                    if(I * (Sheetrows-1) + (J +1) ==RowCount) {                        //Write to clientSystem.IO.MemoryStream ms =NewSystem.IO.MemoryStream (); Book.                        Write (MS); Ms. Seek (0, Seekorigin.begin); returnMS; }                }            }            return NULL; }    }

Call:

/// <summary>        ///Export Excel/// </summary>        /// <param name= "Request" >Request Parameter Collection</param>        /// <returns></returns>         PublicFileresult Toexcel (activerecordrequest request) {//Get record informationresponse<Object> listinfo = This.            Crmservice.getactiverecordlist (Request); //initialize requires export fieldList<exportfieldinfo> FieldInfo =NewList<exportfieldinfo>(); Fieldinfo.add (NewExportfieldinfo () {FieldName="activedate", DisplayName="Event Date", DataType=datatypeenum.date}); Fieldinfo.add (NewExportfieldinfo () {FieldName="Activesubject", DisplayName="Event Theme", DataType=datatypeenum.string}); Fieldinfo.add (NewExportfieldinfo () {FieldName="Remark", DisplayName="Notes", DataType=datatypeenum.string}); returnFile (Excelhelper.toexcel (Listinfo.data, FieldInfo),"Application/vnd.ms-excel","activity Information Sheet. xls"); }

JS Call:

// Export to Excel     toexcel:function () {        "/""/""  /toexcel? Ispaging=false";    }

MVC npoi LINQ export Excel general Class

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.