C# NPOI The supplied data appears to be in the Office 2007+ XML. You are calling

C# NPOI 導入與導出Excel文檔 兼容xlsx, xls

分別用到6個類庫,分別是:

NPOI.dll

NPOI.OOXML.dll

NPOI.OpenXml4Net.dll

NPOI.OpenXmlFormats.dll

NPOI.XML

ICSharpCode.SharpZipLib.dll

類目在demo包裏面,目錄:NPOIDemo / NPOIDemoWeb / NPOIDemoWeb / NPOIDLL

完整demo地址:https://download.csdn.net/download/qq_23663693/12370014

 

項目頁面代碼如下:

@model IEnumerable<NPOIDemoWeb.Model.ModelStudent>
@{
    ViewBag.Title = "About";
    <script type="text/javascript" src="@Url.Content("~/Scripts/jquery-1.10.2.min.js")"></script>
    <script type="text/javascript">
        $(function () {
            //當選擇上傳文件改變時
            $("#upLoadFile").change(function () {
                var val = $("#upLoadFile").val().substr($("#upLoadFile").val().lastIndexOf(".") + 1, 4);

                if (val.toLowerCase() == "xls" || val.toLowerCase() == "xlsx") {
                    $("#submitBtn").click();//form表單post提交
                } else {
                    alert('上傳文件格式不正確,只能上傳“.xls”格式文件!');
                }
            });
        });
        //
        function NowImport() {
            alert('將數據保存到自己的數據庫即可!')
        }
    </script>
}

@using (Html.BeginForm("About", "Home", new { classId = @ViewData["ClassId"]}, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <div id="container" style="width: 100%;margin:20px auto 0px auto;padding-left: 40px;">
        <div>
            <font class="fontClass">請選擇.xls格式文件:</font>
            <input type="file" style="width: 260px;" id="upLoadFile" name="upLoadFile" accept=".xls,.xlsx" /> &nbsp;&nbsp;
            <input type="submit" id="submitBtn" name="submitBtn" style="display: none" />
        </div>
    </div>
    <div id="result" style="width: 90%; height: 330px; border: 1px solid #DDDDDD;margin-top: 20px;margin:20px auto 0px auto; text-align: center;overflow-y: auto;overflow-x:hidden">
        <div id="studentList" style="width: 100%;">
            @{
                if (Model != null)
                {
                    <div style="width: 100%;height: 40px;line-height:40px; border-bottom:1px solid #d0cfcf;background-color: #d0cfcf;font-weight: bold ">
                        <div class="head_Td" style="width:100px;float:left;">學號</div>
                        <div class="head_Td" style="width:100px;float:left;">手機號碼</div>
                        <div class="head_Td" style="width:100px;float:left;">姓名</div>
                        <div class="head_Td" style="width:150px;float:left;">身份證號</div>
                        <div class="head_Td" style="width:100px;float:left;">性別</div>
                    </div>
                    <div id="bodyList" style="width: 100%;height: auto;">
                        @for (int i = 0; i < Model.Count(); i++)
                    {
                            <div class="body_Tr" style="width: 100%;height: 40px;line-height:40px;">
                                <div class="body_Td" style="width:100px;float:left;" title="@Model.ToList()[i].xuehao">@Model.ToList()[i].xuehao</div>
                                <div class="body_Td" style="width:100px;float:left;" title="@Model.ToList()[i].iphone">@Model.ToList()[i].iphone</div>
                                <div class="body_Td" style="width:100px;float:left;" title="@Model.ToList()[i].name">@Model.ToList()[i].name</div>
                                <div class="body_Td" style="width:150px;float:left;" title="@Model.ToList()[i].cardId">@Model.ToList()[i].cardId</div>
                                <div class="body_Td" style="width:100px;float:left;">
                                    @if (Model.ToList()[i].sex == 1)
                                    {<span>女</span>}
                                    else
                                    { <span>男</span>}
                                </div>
                            </div>
                        }
                    </div>
                }
            }
        </div>
    </div>
}
<div class="dRowsStudent" style="text-align:center;margin-top:10px;">
    <div class="dFieldStudent">
        <input type="button" id="btnFileSave" class="k-button k-primary" value="立即導入" οnclick="NowImport()"/>
    </div>
</div>

Controllers 代碼如下:

using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using NPOIDemoWeb.Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace NPOIDemoWeb.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// excel導入學生名單
        /// </summary>
        /// <param name="classId"></param>
        /// <returns></returns>
        public ActionResult About(string classId)
        {
            if (Request.HttpMethod != "POST")
            {
                ViewData["ClassId"] = classId;
                return View();
            }
            else
            {
                ViewData["ClassId"] = classId; //爲了錯誤返回
                HttpFileCollectionBase files = Request.Files; //客戶端上載的文件
                try
                {
                    if (files.Count > 0)
                    {
                        HttpPostedFileBase postedFile = files[0];
                        string fileExt = postedFile.FileName.ToLower().Substring(postedFile.FileName.LastIndexOf(".")); //文件擴展名,不含“.”

                        MemoryStream mfile = new MemoryStream();
                        postedFile.InputStream.CopyTo(mfile);

                        mfile.Position = 0;//解決XSSFWorkbook: EOF in header的問題
                        IWorkbook workbook = null;
                        if (fileExt == ".xls")
                        {
                            workbook = new HSSFWorkbook(mfile);//.xls後綴的excel文件
                        }
                        else if (fileExt == ".xlsx")
                        {
                            workbook = new XSSFWorkbook(mfile);//.xlsx後綴的excel文件
                        }
                        ISheet sheet = workbook.GetSheetAt(0);

                        System.Collections.IEnumerator rows = sheet.GetRowEnumerator();//選手名單

                        List<ModelStudent> list = new List<ModelStudent>();

                        ///////////////////////////////////循環excel////////////////////////////////////////////
                        #region 循環excel
                        rows.MoveNext();//標頭
                        while (rows.MoveNext())//
                        {
                            IRow row = (IRow)rows.Current;
                            object cell1 = row.GetCell(1);
                            if (cell1 != null)
                            {
                                if (Convert.ToString(row.GetCell(0).ToString().Trim()) != "")
                                {
                                    ModelStudent studentInfo = new ModelStudent();
                                    studentInfo.xuehao = (row.GetCell(0) == null) ? "" : Convert.ToString(row.GetCell(0).ToString().Trim());
                                    studentInfo.iphone = (row.GetCell(1) == null) ? "" : Convert.ToString((row.GetCell(1).ToString().Trim()));
                                    studentInfo.name = (row.GetCell(2) == null) ? "" : Convert.ToString((row.GetCell(2).ToString().Trim()));
                                    studentInfo.cardId = (row.GetCell(3) == null) ? "" : Convert.ToString((row.GetCell(3).ToString().Trim()));
                                    studentInfo.sex = (row.GetCell(4) == null) ? 0 : Convert.ToInt32((row.GetCell(4).ToString().Trim()) == "女" ? 1 : 0);
                                    list.Add(studentInfo);
                                }
                                
                            }
                        }
                        #endregion

                        TempData["Student"] = list;
                        return View("About", list);
                    }
                    else
                    {
                        return null;
                    }
                }
                catch (Exception ex)
                {
                    TempData["code"] = ex.Message;
                    return View("Contact");
                }
            }
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
    }
}

Model.ModelStudent 代碼如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NPOIDemoWeb.Model
{
    public class ModelStudent
    {
        /// <summary>
        /// 學號
        /// </summary>
        public string xuehao { get; set; }
        /// <summary>
        /// 手機號
        /// </summary>
        public string iphone { get; set; }

        /// <summary>
        /// 姓名
        /// </summary>
        public string name { get; set; }

        /// <summary>
        /// 證件號碼
        /// </summary>
        public string cardId { get; set; }

        /// <summary>
        /// 性別
        /// </summary>
        public int sex { get; set; }
        /// <summary>

    }
}

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章