NPOI导入excel - 在UI中返回UI而不是返回UI中的表

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (36)

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

我按照这个博客尝试使用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());
        }
    }

请注意,我没有使用过模型

实际结果:

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

预期结果:

单击预览按钮时,应显示表格,显示导入的Excel的内容。

提问于
用户回答回答于

原因

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

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

    $ .ajax({
        类型:“POST”,
        url:“/ BulkEditUserPermissions?handler = Import”,
        url:“/ XYZ / OnPostImport”,//将此行更改为正确的URL
        ...

演示:

扫码关注云+社区

领取腾讯云代金券