导出到Excel

1.使用Npoi,只引用“NPOI.dll”,就可以实现基本导出功能

public class HomeController : Controller
{
    public void Nopi()
    {
        HSSFWorkbook book = new HSSFWorkbook();
        ISheet sheet = book.CreateSheet("sheet1");
        List<User> list = GetUsers();
        IRow row = sheet.CreateRow(0);
        row.CreateCell(0).SetCellValue("ID");
        row.CreateCell(1).SetCellValue("姓名");
        for (int i = 0; i < list.Count; i++)
        {
            row = sheet.CreateRow(i + 1);//初始化第i行
            row.CreateCell(0).SetCellValue(list[i].Id);//第0个单元格初始化并赋值
            row.CreateCell(1).SetCellValue(list[i].Name);
        }
        row = sheet.CreateRow(list.Count + 2);
        row.CreateCell(0).SetCellValue("导出时间:");
        row.CreateCell(1).SetCellValue(DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"));
        //第n行自适应列宽
        sheet.AutoSizeColumn(0);
        sheet.AutoSizeColumn(1);
        System.IO.MemoryStream ms = new System.IO.MemoryStream();
        book.Write(ms);
        Response.AddHeader("Content-Disposition", "attachment; filename=test.xls");
        Response.BinaryWrite(ms.ToArray());
        book = null;
        ms.Close();
        ms.Dispose();
    }
    static List<User> GetUsers()
    {
        List<User> list = new List<User>() {
          new User{Id=1,Name="张三"},
          new User{Id=2,Name="李四"},
          new User{Id=3,Name="王五"}
          };
        return list;
    }
}

  

 $("#btnToExcel2").die().live("click", function () {
        window.open("/Home/Nopi");
    })

   

posted @ 2014-04-02 13:48  豆角米饭  阅读(206)  评论(2编辑  收藏  举报