. NET Webapi Generating Excel

Source: Internet
Author: User

In WebForm, generate Excel, which is typically set response. Content.Headers.ContentType output Type is application/vnd.ms-excel, this is the way of thinking.

It is also possible to do this for every API method. Reference: http://www.cnblogs.com/jizhong/p/3592088.html

A better approach is to set the Requst.header Accept:application/vnd.ms-excel when the client requests it. Purpose: The client set what type, the service side targeted to call the corresponding method, return the corresponding type of file stream, can be configured, extensible, formatter related do not write dead in the concrete method, stripped out.

    var _exporttoexcel = function (clientId) {        var url = serviceBase + ' api/clientstatuslog?clientid= ' +clientid;        Return $http. Get (URL, {headers: {Accept: ' Application/vnd.ms-excel '}, Responsetype: ' Arraybuffer '}). Then (function (re Sponse) {            return response;        });    }

The server adds a formatter to the webapiconfig, and we add the object of the class we write, Class inherits from the System.Net.Http.Formatting.BufferedMediaTypeFormatter Mediatypeformatter. Class overrides the Canwritetype of the parent class, setting the type = = typeof (Clientstatuslogreportdto) or ienumerable<clientstatuslogreportdto>, The Canwritetype method returns True. In this way, directly return Clientstatuslogreportdto or LIST<CLIENTSTATUSLOGREPORTDTO> in the Controller method; The formatter method that you write will generate the logic of Excel, call the WriteToStream method of overriding the parent class, implement the data in the specified format, and return the response.

 

    public static class Webapiconfig    {public        static void Register (httpconfiguration config)        {            // Formatters            CONFIG. Formatters.add (New Clientexcelormatter ());            Config. Formatters.add (New Clientstatuslogexcelormatter ());        }   }    

  

public class Clientstatuslogexcelormatter:bufferedmediatypeformatter {Private Const string mime_type = "Applic        Ation/vnd.ms-excel ";        Private Hssfworkbook WorkBook;            Public Clientstatuslogexcelormatter () {//ADD the supported media type.                Supportedmediatypes.add (New Mediatypeheadervalue (Mime_type)); } public override bool Canwritetype (System.Type type) {if (type = = typeof (Clientstatuslogreportd            To) {return true;                } else {Type enumerabletype = typeof (Ienumerable<clientstatuslogreportdto>);            return Enumerabletype.isassignablefrom (type);        }} public override void WriteToStream (type type, object value, Stream writestream, httpcontent content)            {var clientlist = value as ienumerable<clientstatuslogreportdto>; var currole = Owincontexthelper.getuserrOLE ();                if (clientlist! = null) {Initialize ();                Generatedata (clientlist);            Workbook.write (Writestream);                } else {var singleobj = value as Clientstatuslogreportdto;                if (singleobj = = null) {throw new InvalidOperationException ("Cannot serialize type");            }} var filename = "Clientstatuslog.xls"; Content.            Headers.contenttype = new Mediatypeheadervalue (mime_type); Content.            Headers.add ("X-filename", filename); Content.            Headers.contentdisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue ("attachment"); Content.        Headers.ContentDisposition.FileName = FileName;            } private void Initialize () {workBook = new Hssfworkbook (); Create a entry of Documentsummaryinformation DocumentsumMaryinformation dsi = Propertysetfactory.createdocumentsummaryinformation ();            Dsi.company = "Centria Healthcare";            workbook.documentsummaryinformation = DSi;             Create a entry of summaryinformation summaryinformation si = propertysetfactory.createsummaryinformation (); Si.            Subject = "Client Status Log Export";        Workbook.summaryinformation = si; } private void Generatedata (ienumerable<clientstatuslogreportdto> clientlist) {hssfsheet O            Hssfsheet = (hssfsheet) workbook.createsheet ("Client List"); ==================================== string[] columnlist = {"Name", "Funding Source", "Current Status", "Sta            Tus "," Timestamp "," Creator "," Updater "};            int colcount = Columnlist.length;            int rowNum = 0;            int colnum = 0;            IFont Fontheader = Workbook.createfont ();            Fontheader.fontname = "Arial"; Fontheader.boldweight= (short) fontboldweight.bold;            Fontheader.fontheightinpoints = 10;            IFont Fontrow = Workbook.createfont ();            Fontrow.fontname = "Arial";            Fontrow.fontheightinpoints = 10;            Hssfcellstyle HeaderStyle = (hssfcellstyle) workbook.createcellstyle ();            Hssfcellstyle Normalrowstyle = (hssfcellstyle) workbook.createcellstyle ();            Headerstyle.setfont (Fontheader);            Headerstyle.borderbottom = Borderstyle.thin;            Headerstyle.borderleft = Borderstyle.thin;            Headerstyle.borderright = Borderstyle.thin;            Headerstyle.bordertop = Borderstyle.thin;            Headerstyle.alignment = HorizontalAlignment.Center;            Headerstyle.verticalalignment = Verticalalignment.center;            Headerstyle.fillforegroundcolor = HSSFColor.Black.Index;            Normalrowstyle.setfont (Fontrow);            Normalrowstyle.borderbottom = Borderstyle.thin; Normalrowstyle.borderleft = BorderSTyle.            Thin;            Normalrowstyle.borderright = Borderstyle.thin;            Normalrowstyle.bordertop = Borderstyle.thin;            Normalrowstyle.alignment = HorizontalAlignment.Center;            Normalrowstyle.verticalalignment = Verticalalignment.center;            Normalrowstyle.fillforegroundcolor = HSSFColor.Black.Index;            Hssfrow Header = (hssfrow) ohssfsheet.createrow (0); for (int i = 0; i < ColCount; i++) {Hssfcell Ocell = (Hssfcell) header.                Createcell (i);                Ocell.setcelltype (celltype.string);                Ocell.setcellvalue (Columnlist[i]);            Ocell.cellstyle = HeaderStyle;            }//write each item. foreach (Clientstatuslogreportdto client in clientlist) {Hssfrow DataRow = (hssfrow) ohssfsheet.                CreateRow (++rownum);                Colnum = 0; foreach (PropertyInfo proinfo in typeof (Clientstatuslogreportdto). GetProperties ()) {Object v = proinfo.getvalue (client); String value = String.                    Empty;                    if (v! = null) {value = V.tostring ();                    } Hssfcell cell = (Hssfcell) Datarow.createcell (colnum++); Cell.                    Setcelltype (celltype.string); Cell.                    Setcellvalue (value); Cell.                                    CellStyle = Normalrowstyle;        }}} public override bool Canreadtype (type type) {return false; }            }
public class Clientstatuslogcontroller:apicontroller {private ReadOnly iclientstatuslogservice _CLIENTSTATUSL        Ogservice;        Private ReadOnly Imembershipservice _membershipservice; Public Clientstatuslogcontroller (Iclientstatuslogservice Clientstatuslogservice, Imembershipservice            Membershipservice) {this._clientstatuslogservice = Clientstatuslogservice;        This._membershipservice = Membershipservice; Public list<clientstatuslogreportdto> GetList (Guid clientId) {var List = _clientstatuslo            Gservice.getlist (CLIENTID);            var listdto = new list<clientstatuslogreportdto> (); foreach (var item in list) {var dto = Mapper.map<clientstatuslog, CLIENTSTATUSLOGREPORTDTO&G                t; (item); Dto. CreatedBy = _membershipservice.getuserrealname (dto.                CreatedBy); Dto. CreatedBy = _membershipservice.getuserrealname (dto.             ModifiedBy);   Listdto.add (DTO);        } return listdto; }    }

  

  

. NET Webapi Generating Excel

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.