NPOI 关于导入 excel - 在 UI 中返回 UI 而不是 UI 中的 table

NPOI On importing excel - returning the UI inside UI instead of the table in UI

我需要在 ASP.NET Core 中创建一个视图,它将 excel 作为文件上传形式的输入,并显示 excel 内容的 table UI.

中的文件

我按照这个 blog 尝试使用 NPOI 库来实现我的目的。

我的视图名称 XYZ/Index.cshtml 是:

<form method="post" enctype="multipart/form-data">
    <div class="form-group form-inline" id="uploadFileForm">
        <label id="lblUsersCsvFile">Choose File to Upload:</label> &nbsp;
        <input type="file" class="form-control" name="files" id="fUpload"> &nbsp;
        <label id="lblChooseContainer">Choose Container:</label> &nbsp;
        <select class="form-control" id="dropdownContainerOfCsv">
            <option> -- select an option -- </option>
            <option> Group Container </option>
            <option> Application Container </option>
        </select>

    </div>

    <div class="form-group">
        <div class="col-md-10">
            <input type="button" id="btnPreviewCsv" value="Preview" />
        </div>
    </div>

    <br />

    <div id="dvData"></div>

</form>


@section Scripts
{
    <script type="text/javascript">
        $(document).ready(function () {
            $('#btnPreviewCsv').on('click', function () {
                var fileExtension = ['xls', 'xlsx'];
                var filename = $('#fUpload').val();

                if (filename.length == 0) {
                    alert("Please select a file.");
                    return false;
                }
                else {
                    var extension = filename.replace(/^.*\./, '');
                    if ($.inArray(extension, fileExtension) == -1) {
                        alert("Please select only excel files with extension .xls or .xlsx.");
                        return false;
                    }
                }
                var fdata = new FormData();
                var fileUpload = $("#fUpload").get(0);
                var files = fileUpload.files;
                fdata.append(files[0].name, files[0]);
                $.ajax({
                    type: "POST",
                    url: "/XYZ?handler=Import",
                    beforeSend: function (xhr) {
                        xhr.setRequestHeader("XSRF-TOKEN",
                            $('input:hidden[name="__RequestVerificationToken"]').val());
                    },
                    data: fdata,
                    contentType: false,
                    processData: false,
                    success: function (response) {
                        if (response.length == 0)
                            alert('Some error occured while uploading');
                        else {
                            $('#dvData').html(response);
                        }
                    },
                    error: function (e) {
                        $('#dvData').html(e.responseText);
                    }
                });
            })
        });
    </script>
}

我关联的控制器名称为 XYZController 是:

public class XYZController : Controller
    {
        private IHostingEnvironment _hostingEnvironment;
        public XYZController(IHostingEnvironment hostingEnvironment)
        {
            _hostingEnvironment = hostingEnvironment;
        }

        public IActionResult Index()
        {
            return View();
        }

        public ActionResult OnPostImport()
        {
            IFormFile file = Request.Form.Files[0];
            string folderName = "Upload";
            string webRootPath = _hostingEnvironment.WebRootPath;
            string newPath = Path.Combine(webRootPath, folderName);
            StringBuilder sb = new StringBuilder();
            if (!Directory.Exists(newPath))
            {
                Directory.CreateDirectory(newPath);
            }
            if (file.Length > 0)
            {
                string sFileExtension = Path.GetExtension(file.FileName).ToLower();
                ISheet sheet;
                string fullPath = Path.Combine(newPath, file.FileName);
                using (var stream = new FileStream(fullPath, FileMode.Create))
                {
                    file.CopyTo(stream);
                    stream.Position = 0;
                    if (sFileExtension == ".xls")
                    {
                        HSSFWorkbook hssfwb = new HSSFWorkbook(stream); //This will read the Excel 97-2000 formats  
                        sheet = hssfwb.GetSheetAt(0); //get first sheet from workbook  
                    }
                    else
                    {
                        XSSFWorkbook hssfwb = new XSSFWorkbook(stream); //This will read 2007 Excel format  
                        sheet = hssfwb.GetSheetAt(0); //get first sheet from workbook   
                    }
                    IRow headerRow = sheet.GetRow(0); //Get Header Row
                    int cellCount = headerRow.LastCellNum;
                    sb.Append("<table class='table'><tr>");
                    for (int j = 0; j < cellCount; j++)
                    {
                        NPOI.SS.UserModel.ICell cell = headerRow.GetCell(j);
                        if (cell == null || string.IsNullOrWhiteSpace(cell.ToString())) continue;
                        sb.Append("<th>" + cell.ToString() + "</th>");
                    }
                    sb.Append("</tr>");
                    sb.AppendLine("<tr>");
                    for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++) //Read Excel File
                    {
                        IRow row = sheet.GetRow(i);
                        if (row == null) continue;
                        if (row.Cells.All(d => d.CellType == CellType.Blank)) continue;
                        for (int j = row.FirstCellNum; j < cellCount; j++)
                        {
                            if (row.GetCell(j) != null)
                                sb.Append("<td>" + row.GetCell(j).ToString() + "</td>");
                        }
                        sb.AppendLine("</tr>");
                    }
                    sb.Append("</table>");
                }
            }
            return this.Content(sb.ToString());
        }
    }

请注意,我没有使用模型

实际结果:

单击预览按钮后,UI 将在 div dvData 中再次呈现。我认为这是因为我在命名约定中犯了某种错误,因为它在控制器中调用 Index() 而不是 OnPostImport().

预期结果:

单击预览按钮时,应显示 table,显示导入的 excel 的内容。

原因

您正在将请求发送到 Razor 页面处理程序,同时期望控制器操作来处理它。换句话说,url 不能满足需求

如果您更喜欢使用 XYZController/OnPostImport 的控制器操作,您需要将 url 更改为 [area]/[controller]/[action]。例如:

    $.ajax({
        type: "POST",
        url: "/BulkEditUserPermissions?handler=Import",
        url: "/XYZ/OnPostImport",   // change this line to the correct url
        ...

一个工作演示: