NPOI导入导出Excel


  最近较忙,上一篇文章的其他交换机没时间写,我又遇到一个新需求NPOI导入导出Excel,不多废话了,上源码:

简介:

  NPOI 是 POI 项目的 .NET 版本。POI是一个开源的Java读写Excel、WORD等微软OLE2组件文档的项目, 使用 NPOI 你就可以在没有安装 Office 或者相应环境的机器上对 WORD/EXCEL 文档进行读写。NPOI是构建在POI 3.x版本之上的,它可以在没有安装Office的情况下对Word/Excel文档进行读写操作。

NPOI的优势:

1、完全免费的框架 2、包含了大部分EXCEL的特性(单元格样式、数据格式、公式等等) 3、专业的技术支持服务(24*7全天候) (非免费) 4、支持处理的文件格式包括xls, xlsx, docx. 5、采用面向接口的设计架构( 可以查看 NPOI.SS 的命名空间) 6、同时支持文件的导入和导出 7、基于.net 2.0 也支持xlsx 和 docx格式(当然也支持.net 4.0) 8、你不需要在服务器上安装微软的Office,可以避免版权问题。 9、使用起来比Office PIA的API更加方便,更人性化。 10、你不用去花大力气维护NPOI,NPOI Team会不断更新、改善NPOI,绝对省成本。  

EXCEL导入

        /// 
        /// 导入
        /// 
        /// 
        public JsonResult ExcelImport()
        {
            //var files = Request.Files[0];
            HttpPostedFileBase fileBase = Request.Files[0];
            if (fileBase == null || fileBase.ContentLength <= 0)
            {
                return Json("只能上传Excel文件!");
            }
            try
            {
                //获取文件后缀名
                string FinName = Path.GetExtension(fileBase.FileName);
                //获取文件内容
                Stream streamFile = fileBase.InputStream;
                DataTable dt = new DataTable();
                if (FinName != ".xls" && FinName != ".xlsx")
                {
                    return Json("只能上传Excel文件!");
                }
                else
                {
                    if (FinName == ".xls")
                    {
                        //创建一个webbook,对应一个Excel文件(用于xls文件导入类)
                        HSSFWorkbook book = new HSSFWorkbook(streamFile);
                        dt = HSSFExcel(dt, book);
                    }
                    else
                    {
                        XSSFWorkbook book = new XSSFWorkbook(streamFile);
                        dt = XSSFExcel(dt, book);
                    }
                    if (dt == null)
                    {
                        return Json("导入失败!");
                    }
                    else
                    {
                        return Json("成功");
                    }
                }
            }
            catch (Exception ex)
            {
                return Json("导入失败! " + ex.Message);
            }
        }
        /// 
        /// .xls文件导入
        /// 
        /// 
        /// 
        /// 
        public DataTable HSSFExcel(DataTable dt, HSSFWorkbook book)
        {
            // 在webbook中添加一个sheet,对应Excel文件中的sheet,读取当前表数据,索引是0 
            ISheet sheet = book.GetSheetAt(0);
            //读取行数据
            System.Collections.IEnumerator rows = sheet.GetRowEnumerator();
            for (int i = 0; i < (sheet.GetRow(0).LastCellNum); i++)
            {
                dt.Columns.Add(sheet.GetRow(0).Cells[i].ToString());
            }
            while (rows.MoveNext())
            {
                HSSFRow row = (HSSFRow)rows.Current;
                DataRow dr = dt.NewRow();
                for (int i = 0; i < row.LastCellNum; i++)
                {
                    ICell cell = row.GetCell(i);
                    if (cell == null)
                    {
                        dr[i] = null;
                    }
                    else
                    {
                        dr[i] = cell.ToString();
                    }
                    if (cell != null)
                    {
                        if (cell.CellType == CellType.Numeric && DateUtil.IsCellDateFormatted(cell))
                        {
                            dr[i] = cell.DateCellValue.ToString("yyyyMMdd HH:ss");
                        }
                        else
                        {
                            dr[i] = row.GetCell(i).ToString();
                        }
                    }
                }
                dt.Rows.Add(dr);
            }
            dt.Rows.RemoveAt(0);
            return dt;
        }
        /// 
        /// .xlsx文件导入
        /// 
        /// 
        /// 
        /// 
        public DataTable XSSFExcel(DataTable dt, XSSFWorkbook book)
        {
            ISheet sheet = book.GetSheetAt(0);
            System.Collections.IEnumerator rows = sheet.GetRowEnumerator();
            for (int i = 0; i < (sheet.GetRow(0).LastCellNum); i++)
            {
                dt.Columns.Add(sheet.GetRow(0).Cells[i].ToString());
            }
            while (rows.MoveNext())
            {
                XSSFRow row = (XSSFRow)rows.Current;
                DataRow dr = dt.NewRow();
                for (int i = 0; i < row.LastCellNum; i++)
                {
                    ICell cell = row.GetCell(i);
                    if (cell == null)
                    {
                        dr[i] = null;
                    }
                    else
                    {
                        dr[i] = cell.ToString();
                    }
                    if (cell != null)
                    {
                        if (cell.CellType == CellType.Numeric && DateUtil.IsCellDateFormatted(cell))
                            dr[i] = cell.DateCellValue.ToString("yyyy/MM/dd HH:ss:mm");
                        else
                        {
                            dr[i] = row.GetCell(i).ToString();
                        }
                    }
                }
                dt.Rows.Add(dr);
            }
            dt.Rows.RemoveAt(0);
            return dt;
        }

Excel导出:

   
 public JsonResult ExcelExport()
        {
            List list = new List() {
                   new User (){  Id=1, Age=20, Name="yanboling", Sex=""},
                   new User() { Id = 1, Age = 22, Name = "PANLIW", Sex = "" },
                   new User() { Id = 1, Age = 21, Name = "CEHNGSHIQI", Sex = "" },
                   new User() { Id = 1, Age = 23, Name = "WANGTAO", Sex = "" }
                };

            var dt = ToDataTable(list);
            TableToExcel(dt, @"G:\狗粮管够.xls");
            return Json("成功");
        }
  public static void TableToExcel(DataTable dt, string file)
        {
            IWorkbook workbook;
            //创建workbook
            string fileExt = Path.GetExtension(file).ToLower();
            if (fileExt == ".xlsx")
            {
                workbook = new XSSFWorkbook();
            }
            else if (fileExt == ".xls")
            {
                workbook = new HSSFWorkbook();
            }
            else
            {
                workbook = null;
            }
            if (workbook == null)
            {
                return;
            }
            ISheet sheet = string.IsNullOrEmpty(dt.TableName) ? workbook.CreateSheet("Sheet1") : workbook.CreateSheet(dt.TableName);

            //表头  
            IRow row = sheet.CreateRow(0);
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                ICell cell = row.CreateCell(i);
                cell.SetCellValue(dt.Columns[i].ColumnName);
            }

            //数据  
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                IRow row1 = sheet.CreateRow(i + 1);
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    ICell cell = row1.CreateCell(j);
                    cell.SetCellValue(dt.Rows[i][j].ToString());
                }
            }
            //转为字节数组  
            MemoryStream stream = new MemoryStream();
            workbook.Write(stream);
            var buf = stream.ToArray();

            //保存为Excel文件  
            using (FileStream fs = new FileStream(file, FileMode.Create, FileAccess.Write))
            {
                fs.Write(buf, 0, buf.Length);
                fs.Flush();
            }
        }

list转DataTable:

   public static DataTable ToDataTable(List items)
        {
            var tb = new DataTable(typeof(T).Name);

            PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
            foreach (PropertyInfo prop in props)
            {
                Type t = prop.PropertyType;//GetCoreType(prop.PropertyType);
                tb.Columns.Add(prop.Name, t);
            }

            foreach (T item in items)
            {
                var values = new object[props.Length];

                for (int i = 0; i < props.Length; i++)
                {
                    values[i] = props[i].GetValue(item, null);
                }

                tb.Rows.Add(values);
            }

            return tb;
        }
        public static Type GetCoreType(Type t)
        {
            if (t != null && !"".Equals(t))
            {
                if (!t.IsValueType)
                {
                    return t;
                }
                else
                {
                    return Nullable.GetUnderlyingType(t);
                }
            }
            else
            {
                return t;
            }
        }


      public class User
      {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Sex { get; set; }
        public int Age { get; set; }
      }

 

源码:

百度网盘:

链接:https://pan.baidu.com/s/1m6Hv50AqhEJRudP6u7Jx1w
提取码:2180

 

相关