.NET WebAPI生成Excel

Webform中,生成Excel,通常是設置response.Content.Headers.ContentType輸出類型爲application/vnd.ms-excel,思路都是這樣的。javascript

每個API方法都這樣作一下,也是能夠的。參考:http://www.cnblogs.com/jizhong/p/3592088.htmlhtml

 

更好的作法是,客戶端請求的時候,設置Requst.Header的Accept:application/vnd.ms-excel。目的:客戶端設置了什麼類型,服務端針對性的去調用相應方法,返回相應類型的文件流,可配置,可擴展,Formatter相關不寫死在具體方法中,剝離出來。java

	    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 (response) {
	            return response;
	        });
	    }

 

服務端在WebApiConfig中添加一種Formatter,咱們添加本身寫的類的對象,類繼承自System.Net.Http.Formatting.BufferedMediaTypeFormatter的MediaTypeFormatter。類中重寫了父類的CanWriteType,設置type == typeof(ClientStatusLogReportDto)或者IEnumerable<ClientStatusLogReportDto>時候,CanWriteType方法返回true. 這樣在Controller方法中,直接return ClientStatusLogReportDto或List<ClientStatusLogReportDto>, 本身寫的Formatter方法會進行生成Excel的邏輯,調用重寫父類的WriteToStream等方法,實現生成指定格式的數據,返回響應。api

 

    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 = "application/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(ClientStatusLogReportDto))
            {
                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 oHSSFSheet = (HSSFSheet)workBook.CreateSheet("Client List");
            //====================================
            string[] columnList = { "Name", "Funding Source", "Current Status", "Status", "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 _clientStatusLogService;
        private readonly IMembershipService _membershipService;
        public ClientStatusLogController(IClientStatusLogService clientStatusLogService, IMembershipService membershipService) 
        {
            this._clientStatusLogService = clientStatusLogService;
            this._membershipService = membershipService;
        }

        public List<ClientStatusLogReportDto> GetList(Guid clientId)
        {
            var list = _clientStatusLogService.GetList(clientId);
            var listDto = new List<ClientStatusLogReportDto>();
            foreach (var item in list)
            {
                var dto = Mapper.Map<ClientStatusLog, ClientStatusLogReportDto>(item);
                dto.CreatedBy = _membershipService.GetUserRealName(dto.CreatedBy);
                dto.CreatedBy = _membershipService.GetUserRealName(dto.ModifiedBy);
                listDto.Add(dto);
            }
            return listDto;
        }

    }
相關文章
相關標籤/搜索