zoukankan      html  css  js  c++  java
  • 使用web API和NPOI导出Excel

    使用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;
    

      

  • 相关阅读:
    TensorFlow 基础 (04)
    面向对象编程思想的介绍
    B2B、B2C、C2C、O2O的概念
    为什么我们需要域
    如何在阿里云服务器上搭建wordpress个人网站
    Ghost手动备份、还原系统详细图文教程
    IE浏览器下载文件保存时提示:“你没有权限在此位置中保存文件”解决办法
    电脑经常自动重启的一些解决办法
    ERP系统到底能做什么?
    SQL实用技巧:如何分割字符串
  • 原文地址:https://www.cnblogs.com/lvfeilong/p/546ffhgfh.html
Copyright © 2011-2022 走看看