You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET MVC中Excel上传SQL数据库表的文件获取问题

问题分析与解决方案

核心问题

你的代码存在两个关键问题:

  1. 文件名称不匹配:视图中文件上传控件的name="File",但后台用Request.Files["UploadedFile"]获取,名称不一致导致返回null
  2. 流读取冲突:先调用file.InputStream.Read读取字节数组后,流指针移到末尾,后续ExcelPackage读取流时会无数据可用

修复步骤与代码修改

1. 修正文件名称匹配(二选一)

  • 方案一:修改视图控件名称
    把视图里的文件输入框name改为和后台一致的UploadedFile:
<input type="file" name="UploadedFile" accept=".xls,.xlsx" id="btn-choose" />
  • 方案二:后台使用正确名称获取
    将后台获取文件的代码改为:
HttpPostedFileBase file = Request.Files["File"];

2. 优化Action方法(推荐写法)

直接用HttpPostedFileBase作为Action参数替代FormCollection,同时修复流读取问题、增加空值容错:

[HttpPost]
public ActionResult FileUpload(HttpPostedFileBase UploadedFile)
{
    var userList = new List<Employee_table>();
    if (UploadedFile != null && UploadedFile.ContentLength > 0 && !string.IsNullOrEmpty(UploadedFile.FileName))
    {
        // 重置流位置,避免前置读取导致流为空
        UploadedFile.InputStream.Position = 0;
        using (var package = new ExcelPackage(UploadedFile.InputStream))
        {
            ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
            var workSheet = package.Workbook.Worksheets.First();
            var noOfRow = workSheet.Dimension.End.Row;
            
            for (int rowIterator = 2; rowIterator <= noOfRow; rowIterator++)
            {
                // 空值判断,避免Convert.ToInt32报错
                var yearValue = workSheet.Cells[rowIterator, 1].Value;
                if (yearValue == null) continue;
                
                var user = new Employee_table();
                user.Year = Convert.ToInt32(yearValue);
                user.Month = Convert.ToInt32(workSheet.Cells[rowIterator, 2].Value ?? 0);
                user.Div_Code = Convert.ToInt32(workSheet.Cells[rowIterator, 3].Value ?? 0);
                user.Div_Name = workSheet.Cells[rowIterator, 4].Value?.ToString() ?? string.Empty;
                user.EMP_Code = Convert.ToInt32(workSheet.Cells[rowIterator, 5].Value ?? 0);
                user.EMP_Name = workSheet.Cells[rowIterator, 6].Value?.ToString() ?? string.Empty;
                user.DESG_Code = Convert.ToInt32(workSheet.Cells[rowIterator, 7].Value ?? 0);
                userList.Add(user);
            }
        }
    }
    
    if (userList.Any())
    {
        using (File_UploadEntities excelImportDBEntities = new File_UploadEntities())
        {
            // 批量插入效率更高
            excelImportDBEntities.Employee_table.AddRange(userList);
            int result = excelImportDBEntities.SaveChanges();
            if (result > 0)
            {
                return RedirectToAction("Index");
            }
        }
    }
    return View("Index");
}

3. 完整修改后的视图代码(对应方案一)

<div class="col-md-10">
    @using (Html.BeginForm("FileUpload", "Home", FormMethod.Post, new { @enctype = "multipart/form-data" }))
    {
        <div class="action-buttons">
            <input type="file" name="UploadedFile" accept=".xls,.xlsx" id="btn-choose" />
            <input type="submit" name="Download" value="Download Template" formaction="Download" id="btn-download" class="btn btn-primary"/>
        </div>
        <br />
        <input type="submit" value="Upload Data" id="btn-Upload" formaction="FileUpload" class="btn btn-primary" />
    }
</div>

额外提示

  • 确保项目已正确安装EPPlus包(依赖ExcelPackage)
  • 可增加文件类型严格验证,避免非Excel文件上传
  • 批量插入用AddRange比循环Add性能更优

内容的提问来源于stack exchange,提问作者AMAR SHARMA

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 13:53:19