#region 从Excel导入
/// <summary>
/// 读取excel ,默认第一行为标头
/// </summary>
/// <param name="strFileName">excel文档路径</param>
/// <returns></returns>
public static DataTable ExcelImport(string strFileName)
{
DataTable dt = new DataTable(); ISheet sheet = null;
using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
{
if (strFileName.IndexOf(".xlsx") == -)//
{
HSSFWorkbook hssfworkbook = new HSSFWorkbook(file);
sheet = hssfworkbook.GetSheetAt();
}
else//
{
XSSFWorkbook xssfworkbook = new XSSFWorkbook(file);
sheet = xssfworkbook.GetSheetAt();
}
} System.Collections.IEnumerator rows = sheet.GetRowEnumerator(); IRow headerRow = sheet.GetRow();
int cellCount = headerRow.LastCellNum; for (int j = ; j < cellCount; j++)
{
ICell cell = headerRow.GetCell(j);
dt.Columns.Add(cell.ToString());
} for (int i = (sheet.FirstRowNum + ); i <= sheet.LastRowNum; i++)
{
IRow row = sheet.GetRow(i);
DataRow dataRow = dt.NewRow(); for (int j = row.FirstCellNum; j < cellCount; j++)
{
if (row.GetCell(j) != null)
dataRow[j] = row.GetCell(j).ToString();
} dt.Rows.Add(dataRow);
}
return dt;
}
#endregion
#region RGB颜色转NPOI颜色
private static short GetXLColour(HSSFWorkbook workbook, Color SystemColour)
{
short s = ;
HSSFPalette XlPalette = workbook.GetCustomPalette();
NPOI.HSSF.Util.HSSFColor XlColour = XlPalette.FindColor(SystemColour.R, SystemColour.G, SystemColour.B);
if (XlColour == null)
{
if (NPOI.HSSF.Record.PaletteRecord.STANDARD_PALETTE_SIZE < )
{
XlColour = XlPalette.FindSimilarColor(SystemColour.R, SystemColour.G, SystemColour.B);
s = XlColour.Indexed;
} }
else
s = XlColour.Indexed;
return s;
}
#endregion #region 设置列的对齐方式
/// <summary>
/// 设置对齐方式
/// </summary>
/// <param name="style"></param>
/// <returns></returns>
private static HorizontalAlignment getAlignment(string style)
{
switch (style)
{
case "center":
return HorizontalAlignment.Center;
case "left":
return HorizontalAlignment.Left;
case "right":
return HorizontalAlignment.Right;
case "fill":
return HorizontalAlignment.Fill;
case "justify":
return HorizontalAlignment.Justify;
case "centerselection":
return HorizontalAlignment.CenterSelection;
case "distributed":
return HorizontalAlignment.Distributed;
}
return NPOI.SS.UserModel.HorizontalAlignment.General; } #endregion