using DeviceRepair.Models; using NPOI.SS.UserModel; using System; namespace TsSFCDevice.Client.Launch.Common.NpoiExtend { public static class SheetExtend { /// /// 自定义方法实现 [A,2] 形式的单元格定位 /// /// /// /// public static ICell LocateCellByAddress(this ISheet sheet, string address) { // 解析地址,这里简单处理,假设地址格式总是为 "[列字母,行号]" // 更复杂的Excel地址解析可能需要更详细的逻辑 var parts = address.Trim('[', ']').Split(','); if (parts.Length != 2) { throw new ArgumentException("传入的单元格字符串不正确."); } var columnLetter = parts[0]; int rowIndex; if (!int.TryParse(parts[1], out rowIndex) || rowIndex < 0) { throw new ArgumentException("传入的单元格字符串行号不正确."); } // 将列字母转换为列索引 int columnIndex = ColumnIndexFromLetter(columnLetter); // 获取单元格 IRow row = sheet.GetRow(rowIndex - 1); if (row == null) { row = sheet.CreateRow(rowIndex - 1); } ICell cell = row.GetCell(columnIndex); if (cell == null) { cell = row.CreateCell(columnIndex); } return cell; } /// /// [A,2] 形式的单元格 转 行号及列号 /// /// /// public static SheetDataItem AddressToIndex(string address) { // 解析地址,这里简单处理,假设地址格式总是为 "[列字母,行号]" // 更复杂的Excel地址解析可能需要更详细的逻辑 var parts = address.Trim('[', ']').Split(','); if (parts.Length != 2) { throw new ArgumentException("传入的单元格字符串不正确."); } var columnLetter = parts[0]; int rowIndex; if (!int.TryParse(parts[1], out rowIndex) || rowIndex < 0) { throw new ArgumentException("传入的单元格字符串行号不正确."); } // 将列字母转换为列索引 int columnIndex = ColumnIndexFromLetter(columnLetter); return new SheetDataItem() { RowIndex = rowIndex - 1, ColumnIndex = columnIndex }; } public static int ColumnIndexFromLetter(string columnLetter) { int result = 0; foreach (char c in columnLetter) { result *= 26; result += (c - 'A' + 1); } return result - 1; // 调整索引从0开始 } } }