using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace TempTask.WebEntry.Tools
{
///
///
///
public static class ExcelHelper
{
static ExcelHelper()
{
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
}
///
/// 判断是否为兼容模式
///
///
///
public static bool GetIsCompatible(string filePath)
{
return filePath.EndsWith(".xls", StringComparison.OrdinalIgnoreCase);
}
///
/// 创建工作薄
///
///
///
public static IWorkbook CreateWorkbook(bool isCompatible)
{
if (isCompatible)
{
return new HSSFWorkbook();
}
else
{
return new XSSFWorkbook();
}
}
///
/// 创建工作薄(依据文件流)
///
///
///
///
public static IWorkbook CreateWorkbook(bool isCompatible, dynamic stream)
{
if (isCompatible)
{
return new HSSFWorkbook(stream);
}
else
{
return new XSSFWorkbook(stream);
}
}
///
/// 列名字母转索引
///
///
///
public static int ToExcelColumnIndex(this string columnName)
{
if (!Regex.IsMatch(columnName.ToUpper(), @"[A-Z]+")) { throw new Exception("invalid parameter"); }
int index = 0;
char[] chars = columnName.ToUpper().ToCharArray();
for (int i = 0; i < chars.Length; i++)
{
index += ((int)chars[i] - (int)'A' + 1) * (int)Math.Pow(26, chars.Length - i - 1);
}
return index - 1;
}
///
/// 列索引转字母
///
///
///
public static string ToExcelColumnName(this int index)
{
if (index < 0) { throw new Exception("invalid parameter"); }
List chars = new List();
do
{
if (chars.Count > 0) index--;
chars.Insert(0, ((char)(index % 26 + (int)'A')).ToString());
index = (int)((index - index % 26) / 26);
} while (index > 0);
return String.Join(string.Empty, chars.ToArray());
}
}
}