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;

代碼不難理解,自己琢磨下即可。記錄下來,以備后用。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM