ASP.NET MVC读取Excel数据开源插件:ExcelDataReader

1.  ExcelDataReader 下载地址

2.安装NuGet包

ASP.NET MVC读取Excel数据开源插件:ExcelDataReader_第1张图片

3.引入包之后直接用(简单): 

using Donvv.BLL;
using Donvv.Model;
using ExcelDataReader;
using System.Collections.Generic;
using System.IO;
using System.Web.Mvc;


namespace Donvv.Controllers
{
    public class ExcelReaderController : Controller
    {
        // GET: ExcelReader
        public void GetExcelData()
        {
            string filePath = "E:\\ExcelData\\GoodsType.xlsx"; ;
            using (var stream = System.IO.File.Open(filePath, FileMode.Open, FileAccess.Read))
            {
                //  - OpenXml Excel files (2007 format; *.xlsx)
                using (var reader = ExcelReaderFactory.CreateReader(stream))
                {
                    // Choose one of either 1 or 2:
                    // 1. Use the reader methods
                    //do
                    //{
                    //    while (reader.Read())
                    //    {
                    //        // reader.GetDouble(0);
                    //    }
                    //}
                    //while (reader.NextResult()) ;
                    // 2. Use the AsDataSet extension method
                    var result = reader.AsDataSet();//dataset
                    var goodsTypeList = new List();//待更新列表
                    BaseManage bm = new BaseManage();
                    var sheet = result.Tables["Sheet1"];//datatable
                    for (int i = 1; i < sheet.Rows.Count; i++) //行
                    {
                        var code = (sheet.Rows[i][0]).ToString();//编码
                        var name = sheet.Rows[i][1].ToString();//品牌名称
                        if (code.Length == 3)
                        {
                            goodsTypeList.Add(new GoodsTypeUpdate
                            {
                                TypeCode = code,
                                TypeName = name,
                                Level = 1
                            });
                        }
                        else if (code.Length == 5)
                        {
                            goodsTypeList.Add(new GoodsTypeUpdate
                            {
                                TypeCode = code,
                                TypeName = name,
                                Level = 2
                            });
                        }
                        else
                        {
                            goodsTypeList.Add(new GoodsTypeUpdate
                            {
                                TypeCode = code,
                                TypeName = name,
                                Level = 3
                            });
                        }
                    }
                    bm.Update(goodsTypeList);
                }
             }
        }
    }
}

 

你可能感兴趣的:(ASP.NET,C#,MVC)