63 lines
1.9 KiB
C#
63 lines
1.9 KiB
C#
|
using NPOI.SS.UserModel;
|
|||
|
using System;
|
|||
|
|
|||
|
namespace DeviceRepairAndOptimization.Common.NpoiExtend
|
|||
|
{
|
|||
|
public static class SheetExtend
|
|||
|
{
|
|||
|
|
|||
|
/// <summary>
|
|||
|
/// 自定义方法实现 [A,2] 形式的单元格定位
|
|||
|
/// </summary>
|
|||
|
/// <param name="sheet"></param>
|
|||
|
/// <param name="address"></param>
|
|||
|
/// <returns></returns>
|
|||
|
public static ICell LocateCellByAddress(this ISheet sheet, string address)
|
|||
|
{
|
|||
|
// 解析地址,这里简单处理,假设地址格式总是为 "[列字母,行号]"
|
|||
|
// 更复杂的Excel地址解析可能需要更详细的逻辑
|
|||
|
var parts = address.Trim('[', ']').Split(',');
|
|||
|
if (parts.Length != 2)
|
|||
|
{
|
|||
|
throw new ArgumentException("Invalid cell address format.");
|
|||
|
}
|
|||
|
|
|||
|
var columnLetter = parts[0];
|
|||
|
int rowIndex;
|
|||
|
if (!int.TryParse(parts[1], out rowIndex) || rowIndex < 0)
|
|||
|
{
|
|||
|
throw new ArgumentException("Invalid row index.");
|
|||
|
}
|
|||
|
|
|||
|
// 将列字母转换为列索引
|
|||
|
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;
|
|||
|
}
|
|||
|
|
|||
|
private static int ColumnIndexFromLetter(string columnLetter)
|
|||
|
{
|
|||
|
int result = 0;
|
|||
|
foreach (char c in columnLetter)
|
|||
|
{
|
|||
|
result *= 26;
|
|||
|
result += (c - 'A' + 1);
|
|||
|
}
|
|||
|
return result - 1; // 调整索引从0开始
|
|||
|
}
|
|||
|
}
|
|||
|
}
|