标签:
简介:包含:获取单元格合并信息GetMergedCellAddress、获取引用单元格字符串ConvertAddressToString、获取单元格字符串格式内容CellValueToString
public class ExcelHelper { /// <summary> /// Return cell‘s CellRangeAddress if that is a merged cell, otherwise return null /// </summary> /// <param name="cell">the cell will be checked</param> /// <returns>the cell‘s CellRangeAddress</returns> public static CellRangeAddress GetMergedCellAddress(ICell cell) { //not merged cell if (cell.IsMergedCell == false) return null; int MergedRegionsNum = cell.Sheet.NumMergedRegions; for(int index = 0; index < MergedRegionsNum; index++) { CellRangeAddress address = cell.Sheet.GetMergedRegion(index); if (address.FirstRow == cell.RowIndex && address.FirstColumn == cell.ColumnIndex) return address; } //no match return null; } /// <summary> /// 将Excel行列索引号(从0开始)转换为引用地址,分非R1C1格式(默认)和R1C1格式 /// </summary> /// <param name="rowIndex">行索引号(从0开始)</param> /// <param name="columnIndex">列索引号(从0开始)</param> /// <param name="isR1C1Format">是否R1C1格式(默认为否)</param> /// <returns>Excel单元格引用地址字符串</returns> public static string ConvertAddressToString(int rowIndex, int columnIndex, bool isR1C1Format = false) { if (rowIndex < 0 || columnIndex < 0) throw new IndexOutOfRangeException("行/列索引号不可为负数"); if (isR1C1Format) //R1C1格式行号在前列号在后 eg:R2C3 第2行第3列 return string.Format("R{0}C{1}", rowIndex + 1, columnIndex + 1); else { //非R1C1格式列号在前行号在后 eg:C5 第5行第3列 //convert column num to letter int num = columnIndex; string colAddress = string.Empty; while(num > -1) { int remainder = num >= 26 ? num % 26 : num; colAddress = (char)(remainder + 65) + colAddress; num = (num / 26) - 1; } return string.Format("{1}{0}", rowIndex + 1, colAddress); } } /// <summary> /// 获取Excel单元格引用地址,分非R1C1格式(默认)和R1C1格式 /// </summary> /// <param name="cell">引用单元格</param> /// <param name="isR1C1Format">是否R1C1格式(默认为否)</param> /// <returns>Excel单元格引用地址字符串</returns> public static string ConvertAddressToString(ICell cell, bool isR1C1Format = false) { return ConvertAddressToString(cell.RowIndex, cell.ColumnIndex, isR1C1Format); } /// <summary> /// 获取Excel单元格值(字符串格式) /// </summary> /// <param name="cell">单元格</param> /// <returns>单元格字符串格式值内容</returns> public static string CellValueToString(ICell cell) { if (cell == null) return null; switch (cell.CellType) { case CellType.Blank: return string.Empty; case CellType.String: return cell.StringCellValue; case CellType.Boolean: return cell.BooleanCellValue.ToString(); case CellType.Error: return cell.ErrorCellValue.ToString(); case CellType.Formula: return cell.CellFormula; case CellType.Numeric: case CellType.Unknown: default: return cell.ToString(); } } }
标签:
原文地址:http://www.cnblogs.com/KingUp/p/5722551.html