使用NPOI操作Excel

案例:用NPOI动态生成一个Excel表,然后弹出对话框让用户下载,文件名是"用户列表.xls" 先去相关网站下载 NPOI DLL文件,再引用
application/x-excel, application/octet-stream(不知道的类型都可用)
复制代码
   context.Response.ContentType = "application/x-excel";    //设置返回类型
   string name = HttpUtility.UrlEncode("用户列表.xls");
   context.Response.AddHeader("Content-Disposition", "attachment;filename=" + name);
   HSSFWorkbook workbook = new HSSFWorkbook();     //创建 一个 Excel 表
   HSSFSheet sheet = workbook.CreateSheet();       //创建 一个表
   HSSFRow row = sheet.CreateRow(0);               //创建 第一行
   HSSFRow row2 = sheet.CreateRow(1);              //创建 第二行
   HSSFCell cell = row.CreateCell(0, HSSFCell.ENCODING_COMPRESSED_UNICODE); //创建单元格
   cell.SetCellValue("ID");        // 第1行第1列值
   row.CreateCell(1, HSSFCell.ENCODING_COMPRESSED_UNICODE).SetCellValue("姓名"); //第1行第2列值
   row.CreateCell(2, HSSFCell.ENCODING_COMPRESSED_UNICODE).SetCellValue("年龄"); //第1行第3列值

   row2.CreateCell(0, HSSFCell.ENCODING_COMPRESSED_UNICODE).SetCellValue(1);     // 第2行第1列值
   row2.CreateCell(1, HSSFCell.ENCODING_COMPRESSED_UNICODE).SetCellValue("小高");// 第2行第2列值
   row2.CreateCell(2, HSSFCell.ENCODING_COMPRESSED_UNICODE).SetCellValue(21);   // 第2行第3列值
   workbook.Write(context.Response.OutputStream);    //写入到输出流中
复制代码

然后在HTML页面中调用 <a href="down.asxh">Excel下载</a>

案例:将数据库的内容导入到Excel表中,让用户下载
复制代码
  context.Response.ContentType = "application/x-excel";
   string name = HttpUtility.UrlEncode("用户列表.xls");
   context.Response.AddHeader("Content-Disposition", "attachment;filename=" + name);

   HSSFWorkbook workbook = new HSSFWorkbook();  //先创建Excel文件
   HSSFSheet sheet = workbook.CreateSheet();    //先创建一张表

   using (SqlConnection conn = new SqlConnection("server=.;database=mytest;uid=sa;pwd=gao;"))
    {
          conn.Open();
         IDbCommand cmd = conn.CreateCommand();    //IDbCommand 是一个接口,用 SqlCommand 一样
          cmd.CommandText = "select username,passwd from mydo";
         IDataReader dr = cmd.ExecuteReader();     //IDataReader 也是个接口,用 SqlDataReader 一样
          int rownum = 0;        //定义一个变量,用来操作行数
          while (dr.Read())
           {
             string UserName =Convert.ToString(dr["username"]);    //取得用户名
             string Password = Convert.ToString(dr["passwd"]);  //取得密码
             HSSFRow row = sheet.CreateRow(rownum);        //创建一行,以 rownum 为准

             row.CreateCell(0, HSSFCellType.STRING).SetCellValue(UserName); //第一列为 用户名
             row.CreateCell(1, HSSFCellType.STRING).SetCellValue(Password); //第二列为 密码
             rownum++;            //行数变量自增,即可实现自动插入下一行
            }
     }
     workbook.Write(context.Response.OutputStream);        //将Excel表写入到输出流中
复制代码
原文地址:https://www.cnblogs.com/yezuhui/p/6842702.html