.NET Core Web API使用ExcelPackage获取Excel行数遇XmlException报错求助
解决.NET Core Web API中EPPlus获取Excel行数的XML异常问题
错误原因
你遇到的XmlException是因为XPath表达式中的d:前缀没有在NameSpaceManager中正确绑定对应的XML命名空间URI,导致解析器无法识别带冒号的前缀,抛出了“冒号不能包含在名称中”的错误。
推荐解决方案:使用EPPlus内置属性获取行数
EPPlus本身提供了直接获取工作表行数的属性,无需手动操作XML,代码更简洁可靠:
using OfficeOpenXml; using Microsoft.AspNetCore.Http; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; public static async Task<List<ImportedFileData>> getFileData(IFormFile incomingFile) { var importedFileData = new List<ImportedFileData>(); try { // 针对EPPlus 5+版本,非商用场景需设置许可证上下文 ExcelPackage.LicenseContext = LicenseContext.NonCommercial; using (var stream = new MemoryStream()) { await incomingFile.CopyToAsync(stream); using (var package = new ExcelPackage(stream)) { ExcelWorksheet worksheet = package.Workbook.Worksheets[0]; // 获取包含数据的有效行数,工作表为空时返回0 int rowCount = worksheet.Dimension?.End.Row ?? 0; Console.WriteLine("===row count==="); Console.WriteLine(rowCount); } } } catch(Exception ex) { Console.WriteLine(ex.Message); } return importedFileData; }
说明:
worksheet.Dimension?.End.Row:获取工作表中最后一行有数据的行号,即有效行数。- 若需获取工作表总行数(包括空行),可替换为
worksheet.Dimension?.Rows ?? 0。 - 修正
using语句:正确的命名空间是OfficeOpenXml,而非OfficeOpenXml.Core.ExcelPackage。
备选方案:修复XPath命名空间绑定(仅作参考)
如果一定要通过XML XPath方式获取行数,需先在NameSpaceManager中注册Excel官方命名空间:
using OfficeOpenXml; using Microsoft.AspNetCore.Http; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using System.Xml; public static async Task<List<ImportedFileData>> getFileData(IFormFile incomingFile) { var importedFileData = new List<ImportedFileData>(); try { ExcelPackage.LicenseContext = LicenseContext.NonCommercial; using (var stream = new MemoryStream()) { await incomingFile.CopyToAsync(stream); using (var package = new ExcelPackage(stream)) { ExcelWorksheet worksheet = package.Workbook.Worksheets[0]; // 注册Excel主命名空间,前缀d对应官方URI worksheet.NameSpaceManager.AddNamespace("d", "http://schemas.openxmlformats.org/spreadsheetml/2006/main"); var rowCount = worksheet.WorksheetXml.XPathSelectElements("//d:sheetData/d:row", worksheet.NameSpaceManager).Count(); Console.WriteLine("===row count==="); Console.WriteLine(rowCount); } } } catch(Exception ex) { Console.WriteLine(ex.Message); } return importedFileData; }
内容的提问来源于stack exchange,提问作者Fahad Subzwari
相关产品推荐
相关产品推荐

