NPOI导入导出Excel

.net mvc利用NPOI导入导出excel

1、导出Excel :
首先引用NPOI包,从这里下载》download
(Action一定要用FileResult)

/// <summary>
        /// 批量导出需要导出的列表
        /// </summary>
        /// <returns></returns>
        public FileResult ExportStu2()
        {
            //获取list数据
            var checkList = (from oc in db.OrganizeCustoms
                            join o in db.Organizes.DefaultIfEmpty() on oc.custom_id equals o.id
                            where oc.organize_id == 1
                            select new
                            {
                                customer_id = o.id,
                                customer_name = o.name
                            }).ToList();

            //创建Excel文件的对象
            NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();
            //添加一个sheet
            NPOI.SS.UserModel.ISheet sheet1 = book.CreateSheet("Sheet1");

            //貌似这里可以设置各种样式字体颜色背景等,但是不是很方便,这里就不设置了

            //给sheet1添加第一行的头部标题
            NPOI.SS.UserModel.IRow row1 = sheet1.CreateRow(0);
            row1.CreateCell(0).SetCellValue("编号");
            row1.CreateCell(1).SetCellValue("姓名");
            //....N行

            //将数据逐步写入sheet1各个行
            for (int i = 0; i < checkList.Count; i++)
            {
                NPOI.SS.UserModel.IRow rowtemp = sheet1.CreateRow(i + 1);
                rowtemp.CreateCell(0).SetCellValue(checkList[i].customer_id.ToString());
                rowtemp.CreateCell(1).SetCellValue(checkList[i].customer_name.ToString());
                //....N行
            }
            // 写入到客户端
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            book.Write(ms);
            ms.Seek(0, SeekOrigin.Begin);
            DateTime dt = DateTime.Now;
            string dateTime = dt.ToString("yyMMddHHmmssfff");
            string fileName = "查询结果" + dateTime + ".xls";
            return File(ms, "application/vnd.ms-excel", fileName);
        }

前台直接写就可实现:

@Html.ActionLink("点击导出Excel", "ExportStu2")

这里有一篇专门介绍设置样式的文章:
http://www.cnblogs.com/puzi0315/p/3265958.html
http://blog.csdn.net/xhccom/article/details/7687264
http://blog.csdn.net/bestreally/article/details/23257851
2、导入Excel:
首先说一些前台吧,mvc上传注意必须加 new { enctype = "multipart/form-data" }

<td>
    @using (@Html.BeginForm("ImportStu", "ProSchool", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
        <text>选择上传文件:(工作表名为“Sheet1”,“电脑号”在A1单元格。)</text>
        <input name="file" type="file" id="file" />
        <input type="submit" name="Upload" value="批量导入第一批名册" />
    }
</td>

后台实现:只传路径得出DataTable:

/// <summary>
    /// Excel导入
    /// </summary>
    /// <param name="filePath"></param>
    /// <returns></returns>
    public DataTable ImportExcelFile(string filePath)
    {
      HSSFWorkbook hssfworkbook;
      #region//初始化信息
      try
      {
        using (FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read))
        {
          hssfworkbook = new HSSFWorkbook(file);
        }
      }
      catch (Exception e)
      {
        throw e;
      }
      #endregion

      using (NPOI.SS.UserModel.ISheet sheet = hssfworkbook.GetSheetAt(0))
      {
        DataTable table = new DataTable();
        IRow headerRow = sheet.GetRow(0);//第一行为标题行
        int cellCount = headerRow.LastCellNum;//LastCellNum = PhysicalNumberOfCells
        int rowCount = sheet.LastRowNum;//LastRowNum = PhysicalNumberOfRows - 1

        //handling header.
        for (int i = headerRow.FirstCellNum; i < cellCount; i++)
        {
          DataColumn column = new DataColumn(headerRow.GetCell(i).StringCellValue);
          table.Columns.Add(column);
        }
        for (int i = (sheet.FirstRowNum + 1); i <= rowCount; i++)
        {
          IRow row = sheet.GetRow(i);
          DataRow dataRow = table.NewRow();

          if (row != null)
          {
            for (int j = row.FirstCellNum; j < cellCount; j++)
            {
              if (row.GetCell(j) != null)
                dataRow[j] = GetCellValue(row.GetCell(j));
            }
          }
          table.Rows.Add(dataRow);
        }
        return table;
      }
    }

补充一个类:

/// <summary>
    /// 根据Excel列类型获取列的值
    /// </summary>
    /// <param name="cell">Excel列</param>
    /// <returns></returns>
    private static string GetCellValue(ICell cell)
    {
      if (cell == null){ return string.Empty; }
      switch (cell.CellType)
      {
        case CellType.BLANK:
          return string.Empty;
        case CellType.BOOLEAN:
          return cell.BooleanCellValue.ToString();
        case CellType.ERROR:
          return cell.ErrorCellValue.ToString();
        case CellType.NUMERIC:
        case CellType.Unknown:
        default:
          return cell.ToString();//This is a trick to get the correct value of the cell. NumericCellValue will return a numeric value no matter the cell value is a date or a number
        case CellType.STRING:
          return cell.StringCellValue;
        case CellType.FORMULA:
          try
          {
            HSSFFormulaEvaluator e = new HSSFFormulaEvaluator(cell.Sheet.Workbook);
            e.EvaluateInCell(cell);
            return cell.ToString();
          }
          catch
          {
            return cell.NumericCellValue.ToString();
          }
      }
    }

得到DataTable后,就想怎么操作就怎么操作了。

时间: 2024-10-07 18:14:32

NPOI导入导出Excel的相关文章

.net mvc利用NPOI导入导出excel

1.导出Excel : 首先引用NPOI包,从这里下载>download (Action一定要用FileResult) /// <summary> /// 批量导出需要导出的列表 /// </summary> /// <returns></returns> public FileResult ExportStu2() { //获取list数据 var checkList = (from oc in db.OrganizeCustoms join o i

Excel操作--使用NPOI导入导出Excel为DataTable

1.ExcelHelper封装 1 namespace NPOI操作Excel 2 { 3 public class ExcelHelper 4 { 5 /// <summary> 6 /// DataTable转成Excel,返回一个文件流 7 /// </summary> 8 /// <param name="dataTable"></param> 9 /// <returns></returns> 10 pu

winfrom 使用NPOI导入导出Excel(xls/xlsx)数据到DataTable中

1.通过NUGET管理器下载nopi,在引入命令空间 1 using System; 2 using System.Collections.Generic; 3 using System.Text; 4 using System.IO; 5 using NPOI.SS.UserModel; //NPOI 6 using NPOI.HSSF.Util; //NPOI 7 using NPOI.HSSF.UserModel; //NPOI 8 using NPOI.XSSF.UserModel; /

npoi导入导出excel (泛型)

最近新项目开始了,万能的excel又要上台工作.对于导出代码网上的确很多,合适的没有找到. 我们这边使用的ef + dapper 两套orm框架,他们有一个共同点,都是操作实体对象的.所以导出不能用万能的DataTable了.后面花了一些时间,集合众仙所长,写了一套单excel导入导出的方式.数据源为List<T> public class Excel { /// <summary> /// 导出到sheet中 /// </summary> /// <typepa

ASP.Net MVC利用NPOI导入导出Excel

因近期项目遇到所以记录一下: 1.导出Excel 首先引用NPOI包 (NPOI自行搜索下载) (Action一定要用FileResult) 1 [Localization] 2 /// <summary> 3 /// 导出Table的数据 4 /// </summary> 5 /// <returns></returns> 6 public FileResult ExportExcel() 7 { 8 //string schoolname = "

&lt;转&gt;Npoi导入导出Excel操作&lt;载&gt;

1 //Datatable导出Excel 2 private static void GridToExcelByNPOI(DataTable dt, string strExcelFileName) 3 { 4 try 5 { 6 HSSFWorkbook workbook = new HSSFWorkbook(); 7 ISheet sheet = workbook.CreateSheet("Sheet1"); 8 9 ICellStyle HeadercellStyle = wor

NPOI 导入导出excel 支持 03 07

因为微软的office成本太高了,所以开发项目的时候电脑上没安装office,而是安装了wps.但开发语言用的是C#,所以直接调用微软的office组件是很方便的,但一方面慢,一方面成本高,所以从网上找到了NPOI这个开源的项目.http://npoi.codeplex.com/,引用的dll下载目录 http://npoi.codeplex.com/downloads/get/1476595 并且封装了通用的处理EXCEL 跟DataSet,DataTable的方法.方便调用 以上是代码 (当

简单回顾NPOI导入导出excel文件

当前环境.net4.0 去官方下下载:  NOPI官网 关于NOPI的详细,这里就不再介绍. 在项目中,我们只需引入  NPOI.dll  就可以了. 接下来................................................................ 上代码......... .......................................................... /// <summary> /// 导出 /// </sum

NPOI导入导出Excel (2)

简单演示一下创建一个Workbook对象,添加一个工作表,在工作表中添加一行一列: using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using System.IO;using NPOI.HSSF.UserModel;using NPOI.SS.UserModel;using Sys