Export excel file using web API

使用MVC controller输出excel的例子,自不待言,例子满天飞。

由于本项目使用的是Asp.net MVC API,因此在本项目使用API,实现了文件下载功能。代码的原理很简单,基本上是老外的代码。只是修改了一部分,以使其代码能正常工作(原代码输出的excel是空的)。以下是核心代码:

            HSSFWorkbook workbook = new HSSFWorkbook();
            ISheet sheet = workbook.CreateSheet("sheet1");

            IRow row = sheet.CreateRow(0);
            row.CreateCell(0).SetCellValue("教师姓名");
            row.CreateCell(1).SetCellValue("学校");
            row.CreateCell(2).SetCellValue("年级平均分");
            row.CreateCell(3).SetCellValue("年级最高分");
            row.CreateCell(4).SetCellValue("年级最低分");
            row.CreateCell(5).SetCellValue("全市所处名次");

            sheet.SetColumnWidth(1, 5000);
            sheet.SetColumnWidth(2, 5000);
            sheet.SetColumnWidth(3, 5000);
            sheet.SetColumnWidth(4, 5000);
            sheet.SetColumnWidth(5, 5000);

            for (var i = 0; i < list.Count; i++)
            {
                IRow row1 = sheet.CreateRow(i + 1);
                row1.CreateCell(0).SetCellValue(list[i].XM);
                row1.CreateCell(1).SetCellValue(list[i].XXMC);
                row1.CreateCell(2).SetCellValue(list[i].AVGScore.ToFloat());
                row1.CreateCell(3).SetCellValue(list[i].MaxScore.ToFloat());
                row1.CreateCell(4).SetCellValue(list[i].MinScore.ToFloat());
                row1.CreateCell(5).SetCellValue(list[i].OrderNumber);
            }
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            
            workbook.Write(ms);
            ms.Position = 0;

            var response = new HttpResponseMessage(HttpStatusCode.OK);
            response.Content = new StreamContent(ms);

            response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
            var fileName = "教学排名_" + (Courselist == null || courseID == null ? "全部" : Courselist.Name) + ".xls";
            

response.Content.Headers.ContentDisposition
= new ContentDispositionHeaderValue("attachment") { FileName = System.Web.HttpUtility.UrlEncode(fileName) }; return response;

代码不难理解,自己琢磨下即可。记录下来,以备后用。

 

posted @ 2014-03-10 16:34  Shapley  阅读(3939)  评论(0编辑  收藏  举报