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;
    

      

  • 相关阅读:
    SLAM+语音机器人DIY系列:(二)ROS入门——3.在ubuntu16.04中安装ROS kinetic
    SLAM+语音机器人DIY系列:(二)ROS入门——2.ROS系统整体架构
    2017年 年计划
    125. Valid Palindrome
    一道多树递归面试题
    顺序表查找和有序表查找
    c++中常见概念、关键字等的区别
    两个栈实现一个队列,两个队列实现一个栈
    150. Evaluate Reverse Polish Notation
    堆排序
  • 原文地址:https://www.cnblogs.com/lvfeilong/p/546ffhgfh.html
Copyright © 2011-2022 走看看