NPOI 读取Excel文件
private void buttonExcel_Click(object sender, EventArgs e)
{
FileStream fs = null;
List<ISheet> lstISheet = new List<ISheet>();
string Msg = "";
string filePath = "";
//初始化一个OpenFileDialog类
OpenFileDialog fileDialog = new OpenFileDialog();
//判断用户是否正确的选择了文件
if (fileDialog.ShowDialog() == DialogResult.OK)
{
//获取用户选择文件的后缀名
string extension = Path.GetExtension(fileDialog.FileName);
//声明允许的后缀名
string[] str = new string[] { ".xls", ".xlsx" };
if (!((IList)str).Contains(extension))
{
MessageBox.Show("仅能选择Excel文件");
}
else
{
filePath = fileDialog.FileName;
}
}
if(filePath!="")
{
IWorkbook book2003; IWorkbook book2007;
bool bl2003 = true; bool bl2007 = true;
fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
try
{
book2003 = new HSSFWorkbook(fs);// 2003版本
int t = ;
while (true)
{
try
{
ISheet sheettemp = book2003.GetSheetAt(t);
lstISheet.Add(sheettemp);
t = t + ;
}
catch (Exception ex)
{
break;
}
}
}
catch (Exception ex)
{
bl2003 = false;
Msg = ex.Message.ToString() + "\r\n" + ex.StackTrace.ToString();
fs.Dispose();
fs.Close();
}
//
if(bl2003==false)
{
fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
try
{
book2007 = new XSSFWorkbook(fs);// 2007版本
int t = ;
while (true)
{
try
{
ISheet sheettemp = book2007.GetSheetAt(t);
lstISheet.Add(sheettemp);
t = t+;
}
catch (Exception ex)
{
break;
}
}
}
catch (Exception ex)
{
bl2007 = false;
Msg = ex.Message.ToString() + "\r\n" + ex.StackTrace.ToString();
} }
ReLstDataTable(lstISheet);
fs.Dispose();
fs.Close(); }
}
public List<DataTable> ReLstDataTable(List<ISheet> lstISheet)
{
List<DataTable> lstTable = new List<DataTable>();
for (int t = ; t < lstISheet.Count; t++)
{
ISheet sheet = lstISheet[t];
int rowCount = sheet.LastRowNum;//总行数
if (rowCount > )
{
IRow firstRow = sheet.GetRow();//第一行
int cellCount = firstRow.LastCellNum;//列数
DataTable dt = new DataTable();
int startRow = ;//如果第一行是列名,则从第二行开始读取
for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
{
ICell cell = firstRow.GetCell(i);
if (cell != null)
{
if (cell.StringCellValue != null)
{
DataColumn column = new DataColumn(cell.StringCellValue);
dt.Columns.Add(column);
}
}
}
//------------------------------------------------
//填充行
for (int i = startRow; i <= rowCount; ++i)
{
IRow row = sheet.GetRow(i);
if (row == null) continue; DataRow dataRow = dt.NewRow();
for (int j = row.FirstCellNum; j < cellCount; ++j)
{
ICell cell = row.GetCell(j);
if (cell == null)
{
dataRow[j] = "";
}
else
{
//CellType(Unknown = -1,Numeric = 0,String = 1,Formula = 2,Blank = 3,Boolean = 4,Error = 5,)
switch (cell.CellType)
{
case CellType.Blank:
dataRow[j] = "";
break;
case CellType.Numeric:
short format = cell.CellStyle.DataFormat;
//对时间格式(2015.12.5、2015/12/5、2015-12-5等)的处理
if (format == || format == || format == || format == )
dataRow[j] = cell.DateCellValue;
else
dataRow[j] = cell.NumericCellValue;
break;
case CellType.String:
dataRow[j] = cell.StringCellValue;
break;
}
}
}
dt.Rows.Add(dataRow);
}
//------------------------------------------------
lstTable.Add(dt);
}
}
return lstTable;
}
public class NPOIExcel
{ #region ========================获取Sheet集合========================
/// <summary>
/// 获取工作表列表
/// </summary>
/// <param name="lstsheet"></param>
/// <returns></returns>
public List<string> LstSheetName(List<ISheet> lstsheet)
{
List<string> lst = new List<string>();
for (int i = ; i < lstsheet.Count; i++)
{
lst.Add(lstsheet[i].SheetName);
}
return lst;
}
/// <summary>
/// 返回sheet表集合
/// </summary>
/// <param name="file"></param>
/// <returns></returns>
public List<ISheet> ExcelToISheetList(string file)
{
string fileExt = Path.GetExtension(file).ToLower();
List<ISheet> lstSheet = new List<ISheet>();
bool bl = true;
//XSSFWorkbook 适用XLSX格式:2007以上
try
{
lstSheet = GetExcelSheetList2007(file);
}
catch (Exception ex)
{
bl = false;
}
//HSSFWorkbook 适用XLS格式:2003版
if (bl == false)
{
bl = true;
try
{
lstSheet = GetExcelSheetList2003(file);
}
catch (Exception ex)
{
bl = false;
}
}
return lstSheet;
} /// <summary>
/// 03版获取 sheet列表
/// </summary>
/// <param name="files">文件路径</param>
/// <param name="sheetname">sheet表名</param>
/// <returns>ISheet</returns>
public List<ISheet> GetExcelSheetList2003(string files)
{
List<ISheet> lstsheet = new List<ISheet>();
//HSSFWorkbook 适用XLS格式:2003版
using (FileStream fs = new FileStream(files, FileMode.Open, FileAccess.Read))
{
IWorkbook workbook2003 = new HSSFWorkbook(fs);
int t = ;
while (true)
{
try
{
ISheet sheet = workbook2003.GetSheetAt(t);
if (sheet != null)
{
lstsheet.Add(sheet);
}
else
{
break;
}
}
catch (Exception)
{
break;
}
t = t + ;
}
}
return lstsheet;
}
/// <summary>
///获取 2007版列表
/// </summary>
/// <param name="files">文件路径</param>
/// <param name="sheetname">sheet表名</param>
/// <returns>ISheet</returns>
public List<ISheet> GetExcelSheetList2007(string files)
{
List<ISheet> lstsheet = new List<ISheet>();
//XSSFWorkbook 适用XLSX格式:2007以上
using (FileStream fs = new FileStream(files, FileMode.Open, FileAccess.Read))
{
IWorkbook workbook2007 = new XSSFWorkbook(fs);
int t = ;
while (true)
{
try
{
ISheet sheet = workbook2007.GetSheetAt(t);
if (sheet != null)
{
lstsheet.Add(sheet);
}
else
{
break;
}
}
catch (Exception)
{
break;
}
t = t + ;
}
}
return lstsheet;
}
#endregion========================获取Sheet集合========================
#region ========================获取sheet表数据========================
/// <summary>
/// 获取sheet的所有列
/// </summary>
/// <param name="sheet"></param>
/// <returns></returns>
public List<string> GetSheetColName(ISheet sheet)
{
//表头
IRow header = sheet.GetRow(sheet.FirstRowNum);
List<string> lstSheetColName = new List<string>();
for (int i = ; i < header.LastCellNum; i++)
{
object obj = GetValueType(header.GetCell(i));
if (obj == null || obj.ToString() == string.Empty)
{
lstSheetColName.Add("列" + (i + ));
}
else
{
lstSheetColName.Add(obj.ToString());
}
}
return lstSheetColName;
}
/// <summary>
/// 获取 sheet表数据
/// </summary>
/// <param name="files">文件路径</param>
/// <param name="sheetname">sheet表名</param>
/// <returns>ISheet</returns>
public ISheet GetExcelsheet(string files, string sheetname)
{
List<ISheet> lstsheet = new List<ISheet>();
bool bl = true;
try
{
ISheet sheet = GetExcelsheet2007(files, sheetname);
lstsheet.Add(sheet);
}
catch (Exception ex)
{
bl = false;
}
//HSSFWorkbook 适用XLS格式:2003版
if (bl == false)
{
bl = true;
try
{
ISheet sheet = GetExcelsheet2003(files, sheetname);
lstsheet.Add(sheet);
}
catch (Exception ex)
{
bl = false;
}
}
return lstsheet[]; }
/// <summary>
/// 03版获取 sheet表数据
/// </summary>
/// <param name="files">文件路径</param>
/// <param name="sheetname">sheet表名</param>
/// <returns>ISheet</returns>
public ISheet GetExcelsheet2003(string files, string sheetname)
{
DataTable dt = new DataTable();
ISheet sheet;
//HSSFWorkbook 适用XLS格式:2003版
using (FileStream fs = new FileStream(files, FileMode.Open, FileAccess.Read))
{
IWorkbook workbook2003 = new HSSFWorkbook(fs);
sheet = workbook2003.GetSheet(sheetname);
}
return sheet;
}
/// <summary>
/// 2007
/// </summary>
/// <param name="files">文件路径</param>
/// <param name="sheetname">sheet表名</param>
/// <returns>ISheet</returns>
public ISheet GetExcelsheet2007(string files, string sheetname)
{
ISheet sheet;
//XSSFWorkbook 适用XLSX格式:2007以上
using (FileStream fs = new FileStream(files, FileMode.Open, FileAccess.Read))
{
IWorkbook workbook2007 = new XSSFWorkbook(fs);
sheet = workbook2007.GetSheet(sheetname);
}
return sheet;
}
#endregion========================获取sheet表数据========================
/// <summary>
/// 获取单元格类型
/// </summary>
/// <param name="cell"></param>
/// <returns></returns>
private static object GetValueType(ICell cell)
{
if (cell == null)
return null;
switch (cell.CellType)
{
case CellType.Blank: //BLANK:
return null;
case CellType.Boolean: //BOOLEAN:
return cell.BooleanCellValue;
case CellType.Numeric: //NUMERIC:
return cell.NumericCellValue;
case CellType.String: //STRING:
return cell.StringCellValue;
case CellType.Error: //ERROR:
return cell.ErrorCellValue;
case CellType.Formula: //FORMULA:
default:
return "=" + cell.CellFormula;
}
}
}
public class ZCDExcel
{
/// <summary>
/// 文件路径
/// </summary>
public string FilePath { get; set; } public ZCDExcel()
{ }
/// <summary>
/// 配置Excel文件路径
/// </summary>
/// <param name="files"></param>
public ZCDExcel(string files)
{
FilePath = files;
} #region ========================获取所有sheet表名称的List<string>集合========================
/// <summary>
/// 根据Excel文件名,获取工作表列表
/// </summary>
/// <returns>返回List string 集合</returns>
public List<string> LstSheetName()
{
List<ISheet> lstsheet = ExcelToISheetList(FilePath);
List<string> lst = new List<string>();
for (int i = ; i < lstsheet.Count; i++)
{
lst.Add(lstsheet[i].SheetName);
}
return lst;
}
/// <summary>
/// 根据Excel文件名,获取工作表列表
/// </summary>
/// <param name="files">文件名</param>
/// <returns>返回List string 集合</returns>
public List<string> LstSheetName(string files)
{
List<ISheet> lstsheet = ExcelToISheetList(files);
List<string> lst = new List<string>();
for (int i = ; i < lstsheet.Count; i++)
{
lst.Add(lstsheet[i].SheetName);
}
return lst;
}
/// <summary>
/// List ISheet对象集合 获取工作表列表
/// </summary>
/// <param name="lstsheet">List ISheet 对象集合</param>
/// <returns>返回List string 集合</returns>
public List<string> LstSheetName(List<ISheet> lstsheet)
{
List<string> lst = new List<string>();
for (int i = ; i < lstsheet.Count; i++)
{
lst.Add(lstsheet[i].SheetName);
}
return lst;
}
#endregion========================获取所有sheet表名称的List<string>集合========================
#region ============================获取ISheet对象的List<ISheet>表集合============================
/// <summary>
/// 返回sheet表集合
/// </summary>
/// <returns></returns>
public List<ISheet> ExcelToISheetList()
{
string fileExt = Path.GetExtension(FilePath).ToLower();
List<ISheet> lstSheet = new List<ISheet>();
bool bl = true;
//XSSFWorkbook 适用XLSX格式:2007以上
try
{
lstSheet = GetExcelSheetList2007(FilePath);
}
catch (Exception ex)
{
bl = false;
}
//HSSFWorkbook 适用XLS格式:2003版
if (bl == false)
{
bl = true;
try
{
lstSheet = GetExcelSheetList2003(FilePath);
}
catch (Exception ex)
{
bl = false;
}
}
return lstSheet;
}
/// <summary>
/// 返回sheet表集合
/// </summary>
/// <param name="file">文件路径</param>
/// <returns>ISheet的list集合</returns>
public List<ISheet> ExcelToISheetList(string file)
{
string fileExt = Path.GetExtension(file).ToLower();
List<ISheet> lstSheet = new List<ISheet>();
bool bl = true;
//XSSFWorkbook 适用XLSX格式:2007以上
try
{
lstSheet = GetExcelSheetList2007(file);
}
catch (Exception ex)
{
bl = false;
}
//HSSFWorkbook 适用XLS格式:2003版
if (bl == false)
{
bl = true;
try
{
lstSheet = GetExcelSheetList2003(file);
}
catch (Exception ex)
{
bl = false;
}
}
return lstSheet;
}
#endregion ============================获取ISheet对象的List<ISheet>表集合============================
#region ============================03版和07版获取 List<ISheet>============================
/// <summary>
/// 03版获取 sheet列表
/// </summary>
/// <param name="files">文件路径</param>
/// <param name="sheetname">sheet表名</param>
/// <returns>ISheet</returns>
public List<ISheet> GetExcelSheetList2003(string files)
{
List<ISheet> lstsheet = new List<ISheet>();
//HSSFWorkbook 适用XLS格式:2003版
using (FileStream fs = new FileStream(files, FileMode.Open, FileAccess.Read))
{
IWorkbook workbook2003 = new HSSFWorkbook(fs);
int t = ;
while (true)
{
try
{
ISheet sheet = workbook2003.GetSheetAt(t);
if (sheet != null)
{
lstsheet.Add(sheet);
}
else
{
break;
}
}
catch (Exception)
{
break;
}
t = t + ;
}
}
return lstsheet;
}
/// <summary>
///获取 2007版列表
/// </summary>
/// <param name="files">文件路径</param>
/// <param name="sheetname">sheet表名</param>
/// <returns>ISheet</returns>
public List<ISheet> GetExcelSheetList2007(string files)
{
List<ISheet> lstsheet = new List<ISheet>();
//XSSFWorkbook 适用XLSX格式:2007以上
using (FileStream fs = new FileStream(files, FileMode.Open, FileAccess.Read))
{
IWorkbook workbook2007 = new XSSFWorkbook(fs);
int t = ;
while (true)
{
try
{
ISheet sheet = workbook2007.GetSheetAt(t);
if (sheet != null)
{
lstsheet.Add(sheet);
}
else
{
break;
}
}
catch (Exception)
{
break;
}
t = t + ;
}
}
return lstsheet;
}
#endregion ==============03版和07版获取 List<ISheet>==============
#region ========================获取sheet对象========================
/// <summary>
/// 根据sheet表索引 获取 sheet表数据 ;文件路径需要事先配置好文件路径
/// </summary>
/// <param name="Index">工作表(sheet表)索引</param>
/// <returns>ISheet</returns>
public ISheet GetExcelsheet(int Index)
{
List<ISheet> lstsheet = new List<ISheet>();
bool bl = true;
try
{
ISheet sheet = GetExcelsheet2007(FilePath, Index);
lstsheet.Add(sheet);
}
catch (Exception ex)
{
bl = false;
}
//HSSFWorkbook 适用XLS格式:2003版
if (bl == false)
{
bl = true;
try
{
ISheet sheet = GetExcelsheet2003(FilePath, Index);
lstsheet.Add(sheet);
}
catch (Exception ex)
{
bl = false;
}
}
return lstsheet[];
}
/// <summary>
/// 根据sheet表名 获取 sheet表数据 ;文件路径需要事先配置好文件路径
/// </summary>
/// <param name="sheetname">sheet表名</param>
/// <returns>ISheet</returns>
public ISheet GetExcelsheet(string sheetname)
{
List<ISheet> lstsheet = new List<ISheet>();
bool bl = true;
try
{
ISheet sheet = GetExcelsheet2007(FilePath, sheetname);
lstsheet.Add(sheet);
}
catch (Exception ex)
{
bl = false;
}
//HSSFWorkbook 适用XLS格式:2003版
if (bl == false)
{
bl = true;
try
{
ISheet sheet = GetExcelsheet2003(FilePath, sheetname);
lstsheet.Add(sheet);
}
catch (Exception ex)
{
bl = false;
}
}
return lstsheet[];
}
/// <summary>
/// 根据sheet表索引 获取 sheet表数据
/// </summary>
/// <param name="files">文件路径</param>
/// <param name="Index">工作表(sheet表)索引</param>
/// <returns>ISheet</returns>
public ISheet GetExcelsheet(string files, int Index)
{
List<ISheet> lstsheet = new List<ISheet>();
bool bl = true;
try
{
ISheet sheet = GetExcelsheet2007(files, Index);
lstsheet.Add(sheet);
}
catch (Exception ex)
{
bl = false;
}
//HSSFWorkbook 适用XLS格式:2003版
if (bl == false)
{
bl = true;
try
{
ISheet sheet = GetExcelsheet2003(files, Index);
lstsheet.Add(sheet);
}
catch (Exception ex)
{
bl = false;
}
}
return lstsheet[];
}
/// <summary>
/// 根据sheet表名 获取 sheet表数据
/// </summary>
/// <param name="files">文件路径</param>
/// <param name="sheetname">sheet表名</param>
/// <returns>ISheet</returns>
public ISheet GetExcelsheet(string files, string sheetname)
{
List<ISheet> lstsheet = new List<ISheet>();
bool bl = true;
try
{
ISheet sheet = GetExcelsheet2007(files, sheetname);
lstsheet.Add(sheet);
}
catch (Exception ex)
{
bl = false;
}
//HSSFWorkbook 适用XLS格式:2003版
if (bl == false)
{
bl = true;
try
{
ISheet sheet = GetExcelsheet2003(files, sheetname);
lstsheet.Add(sheet);
}
catch (Exception ex)
{
bl = false;
}
}
return lstsheet[];
} /// <summary>
/// 03版 根据sheet表名 获取 sheet表数据
/// </summary>
/// <param name="files">文件路径</param>
/// <param name="sheetname">sheet表名</param>
/// <returns>ISheet</returns>
public ISheet GetExcelsheet2003(string files, string sheetname)
{
DataTable dt = new DataTable();
ISheet sheet;
//HSSFWorkbook 适用XLS格式:2003版
using (FileStream fs = new FileStream(files, FileMode.Open, FileAccess.Read))
{
IWorkbook workbook2003 = new HSSFWorkbook(fs);
sheet = workbook2003.GetSheet(sheetname);
}
return sheet;
}
/// <summary>
/// 03版 根据sheet表索引 获取 sheet表数据
/// </summary>
/// <param name="files">文件路径</param>
/// <param name="Index">sheet表索引</param>
/// <returns>ISheet</returns>
public ISheet GetExcelsheet2003(string files, int Index)
{
DataTable dt = new DataTable();
ISheet sheet;
//HSSFWorkbook 适用XLS格式:2003版
using (FileStream fs = new FileStream(files, FileMode.Open, FileAccess.Read))
{
IWorkbook workbook2003 = new HSSFWorkbook(fs);
sheet = workbook2003.GetSheetAt(Index);
}
return sheet;
} /// <summary>
/// 2007版 更加sheet表名 获取sheet对象
/// </summary>
/// <param name="files">文件路径</param>
/// <param name="sheetname">sheet表名</param>
/// <returns>ISheet</returns>
public ISheet GetExcelsheet2007(string files, string sheetname)
{
ISheet sheet;
//XSSFWorkbook 适用XLSX格式:2007以上
using (FileStream fs = new FileStream(files, FileMode.Open, FileAccess.Read))
{
IWorkbook workbook2007 = new XSSFWorkbook(fs);
sheet = workbook2007.GetSheet(sheetname);
}
return sheet;
}
/// <summary>
/// 2007版 根据sheet表索引 获取sheet对象
/// </summary>
/// <param name="files">文件路径</param>
/// <param name="Index">sheet表索引</param>
/// <returns>ISheet</returns>
public ISheet GetExcelsheet2007(string files, int Index)
{
ISheet sheet;
//XSSFWorkbook 适用XLSX格式:2007以上
using (FileStream fs = new FileStream(files, FileMode.Open, FileAccess.Read))
{
IWorkbook workbook2007 = new XSSFWorkbook(fs);
sheet = workbook2007.GetSheetAt(Index);//.GetSheet(sheetname);
}
return sheet;
}
#endregion========================获取sheet表数据========================
#region ======================返回工作表数据DataTable或者DataSet======================= /// <summary>
/// 返回第一个sheet表的数据
/// </summary>
/// <returns>返回DataTable</returns>
public DataTable GetFistSheetTable()
{
ISheet sheet = GetExcelsheet(FilePath, );
DataTable dt = GetSheetTable(sheet);
return dt;
}
/// <summary>
/// 返回第一个sheet表的数据
/// </summary>
/// <param name="files">文件路径</param>
/// <returns>返回DataTable</returns>
public DataTable GetFistSheetTable(string files)
{
ISheet sheet = GetExcelsheet(files, );
DataTable dt = GetSheetTable(sheet);
return dt;
}
/// <summary>
/// 返回最后个sheet表的数据
/// </summary>
/// <returns>返回DataTable</returns>
public DataTable GetLastSheetTable()
{
List<string> lst = LstSheetName(FilePath);
ISheet sheet = GetExcelsheet(FilePath, lst.Count - );
DataTable dt = GetSheetTable(sheet);
return dt;
}
/// <summary>
/// 返回最后个sheet表的数据
/// </summary>
/// <param name="files">文件路径</param>
/// <returns>返回DataTable</returns>
public DataTable GetLastSheetTable(string files)
{
List<string> lst = LstSheetName(files);
ISheet sheet = GetExcelsheet(files, lst.Count - );
DataTable dt = GetSheetTable(sheet);
return dt;
}
/// <summary>
/// 返回第一个sheet表的数据
/// </summary>
/// <param name="Index">文件路径</param>
/// <returns>返回DataTable</returns>
public DataTable GetSheetTable(int Index)
{
ISheet sheet = GetExcelsheet(FilePath, Index);
DataTable dt = GetSheetTable(sheet);
return dt;
}
/// <summary>
/// 返回第一个sheet表的数据
/// </summary>
/// <param name="SheetName">工作表名称</param>
/// <returns>返回DataTable</returns>
public DataTable GetSheetTable(string SheetName)
{
ISheet sheet = GetExcelsheet(FilePath, SheetName);
DataTable dt = GetSheetTable(sheet);
return dt;
}
/// <summary>
/// 返回第一个sheet表的数据
/// </summary>
/// <param name="files">文件路径</param>
/// <param name="SheetName">工作表名称</param>
/// <returns>返回DataTable</returns>
public DataTable GetSheetTable(string files,string SheetName)
{
ISheet sheet = GetExcelsheet(files, SheetName);
DataTable dt = GetSheetTable(sheet);
return dt;
}
/// <summary>
/// 返回第一个sheet表的数据
/// </summary>
/// <param name="files">文件路径</param>
/// <param name="Index">工作表索引</param>
/// <returns>返回DataTable</returns>
public DataTable GetSheetTable(string files, int Index)
{
ISheet sheet = GetExcelsheet(files, Index);
DataTable dt = GetSheetTable(sheet);
return dt;
}
/// <summary>
/// 返回 Excel所有工作表的数据
/// </summary>
/// <returns>DataSet</returns>
public DataSet GetSheetDataSet()
{
List<ISheet> LstSheet = ExcelToISheetList(FilePath);
DataSet ds = GetSheetDataSet(LstSheet);
return ds;
}
/// <summary>
/// 返回 Excel所有工作表的数据
/// </summary>
/// <param name="file">Excel文件路径</param>
/// <returns>DataSet</returns>
public DataSet GetSheetDataSet(string file)
{
List<ISheet> LstSheet = ExcelToISheetList(file);
DataSet ds = GetSheetDataSet(LstSheet);
return ds;
} /// <summary>
/// 根据Sheet对象,获取sheet表的数据
/// </summary>
/// <param name="sheet">工作表对象</param>
/// <returns>返回DataTable</returns>
public DataTable GetSheetTable(ISheet sheet)
{
DataTable dt = new DataTable();
dt.TableName = sheet.SheetName;
//表头
IRow header = sheet.GetRow(sheet.FirstRowNum);
List<int> columns = new List<int>();
for (int i = ; i < header.LastCellNum; i++)
{
object obj = GetValueType(header.GetCell(i));
if (obj == null || obj.ToString() == string.Empty)
{
dt.Columns.Add(new DataColumn("列" + (i + ).ToString()));
}
else
{
dt.Columns.Add(new DataColumn(obj.ToString()));
}
columns.Add(i);
}
//数据
for (int i = sheet.FirstRowNum + ; i <= sheet.LastRowNum; i++)
{
DataRow dr = dt.NewRow();
bool hasValue = false;
foreach (int j in columns)
{
dr[j] = GetValueType(sheet.GetRow(i).GetCell(j));
if (dr[j] != null && dr[j].ToString() != string.Empty)
{
hasValue = true;
}
}
if (hasValue)
{
dt.Rows.Add(dr);
}
}
return dt;
}
/// <summary>
/// 根据Sheet对象,获取sheet表的数据
/// </summary>
/// <param name="sheet">工作表对象</param>
/// <returns>返回DataTable</returns>
public DataSet GetSheetDataSet(List<ISheet> LstSheet)
{
DataSet ds = new DataSet();
for (int t = ; t < LstSheet.Count; t++)
{
DataTable dt = new DataTable();
ISheet sheet = LstSheet[t];
if (sheet != null)
{
dt.TableName = sheet.SheetName;
}
//表头
IRow header = sheet.GetRow(sheet.FirstRowNum);
List<int> columns = new List<int>();
for (int i = ; i < header.LastCellNum; i++)
{
object obj = GetValueType(header.GetCell(i));
if (obj == null || obj.ToString() == string.Empty)
{
dt.Columns.Add(new DataColumn("列" + (i + ).ToString()));
}
else
{
dt.Columns.Add(new DataColumn(obj.ToString()));
}
columns.Add(i);
}
//数据
for (int i = sheet.FirstRowNum + ; i <= sheet.LastRowNum; i++)
{
DataRow dr = dt.NewRow();
bool hasValue = false;
foreach (int j in columns)
{
dr[j] = GetValueType(sheet.GetRow(i).GetCell(j));
if (dr[j] != null && dr[j].ToString() != string.Empty)
{
hasValue = true;
}
}
if (hasValue)
{
dt.Rows.Add(dr);
}
}
ds.Tables.Add(dt);
}
return ds;
}
#endregion ======================返回工作表数据DataTable或者DataSet=======================
#region ==============================获取特定的sheet的所有列的名称=============================
/// <summary>
/// 根据Sheet表索引,获取sheet的所有列的名称
/// </summary>
/// <param name="Index">Sheet表的索引</param>
/// <returns> List字符串集合 列名称 </returns>
public List<string> GetSheetColName(int Index)
{
ISheet sheet = GetExcelsheet(FilePath, Index);
//表头
IRow header = sheet.GetRow(sheet.FirstRowNum);
List<string> lstSheetColName = new List<string>();
for (int i = ; i < header.LastCellNum; i++)
{
object obj = GetValueType(header.GetCell(i));
if (obj == null || obj.ToString() == string.Empty)
{
lstSheetColName.Add("列" + (i + ));
}
else
{
lstSheetColName.Add(obj.ToString());
}
}
return lstSheetColName;
}
/// <summary>
/// 获取最后一个sheet表的所有列的名称
/// </summary>
/// <returns> List字符串集合 列名称 </returns>
public List<string> GetLastSheetColName()
{
List<string> lst = LstSheetName(FilePath);
ISheet sheet = GetExcelsheet(FilePath,lst.Count-);
//表头
IRow header = sheet.GetRow(sheet.FirstRowNum);
List<string> lstSheetColName = new List<string>();
for (int i = ; i < header.LastCellNum; i++)
{
object obj = GetValueType(header.GetCell(i));
if (obj == null || obj.ToString() == string.Empty)
{
lstSheetColName.Add("列" + (i + ));
}
else
{
lstSheetColName.Add(obj.ToString());
}
}
return lstSheetColName;
}
/// <summary>
/// 获取最后一个sheet表的所有列的名称
/// </summary>
/// <param name="Files">文件路径</param>
/// <returns> List字符串集合 列名称 </returns>
public List<string> GetLastSheetColName(string Files)
{
List<string> lst = LstSheetName(FilePath);
ISheet sheet = GetExcelsheet(Files, lst.Count-);
//表头
IRow header = sheet.GetRow(sheet.FirstRowNum);
List<string> lstSheetColName = new List<string>();
for (int i = ; i < header.LastCellNum; i++)
{
object obj = GetValueType(header.GetCell(i));
if (obj == null || obj.ToString() == string.Empty)
{
lstSheetColName.Add("列" + (i + ));
}
else
{
lstSheetColName.Add(obj.ToString());
}
}
return lstSheetColName;
}
/// <summary>
/// 根据Sheet表名称,获取sheet的所有列的名称
/// </summary>
/// <returns> List字符串集合 列名称 </returns>
public List<string> GetSheetColName(string SheetName)
{
ISheet sheet = GetExcelsheet(FilePath, SheetName);
//表头
IRow header = sheet.GetRow(sheet.FirstRowNum);
List<string> lstSheetColName = new List<string>();
for (int i = ; i < header.LastCellNum; i++)
{
object obj = GetValueType(header.GetCell(i));
if (obj == null || obj.ToString() == string.Empty)
{
lstSheetColName.Add("列" + (i + ));
}
else
{
lstSheetColName.Add(obj.ToString());
}
}
return lstSheetColName;
}
/// <summary>
/// 根据Sheet对象,获取sheet的所有列的名称
/// </summary>
/// <param name="sheet">ISheet 对象</param>
/// <returns> List字符串集合 列名称 </returns>
public List<string> GetSheetColName(ISheet sheet)
{
//表头
IRow header = sheet.GetRow(sheet.FirstRowNum);
List<string> lstSheetColName = new List<string>();
for (int i = ; i < header.LastCellNum; i++)
{
object obj = GetValueType(header.GetCell(i));
if (obj == null || obj.ToString() == string.Empty)
{
lstSheetColName.Add("列" + (i + ));
}
else
{
lstSheetColName.Add(obj.ToString());
}
}
return lstSheetColName;
}
/// <summary>
/// 根据Sheet表索引,获取sheet的所有列的名称
/// </summary>
/// <param name="Index">Sheet表的索引</param>
/// <returns> List字符串集合 列名称 </returns>
public List<string> GetSheetColName(string files, int Index)
{
ISheet sheet = GetExcelsheet(files, Index);
//表头
IRow header = sheet.GetRow(sheet.FirstRowNum);
List<string> lstSheetColName = new List<string>();
for (int i = ; i < header.LastCellNum; i++)
{
object obj = GetValueType(header.GetCell(i));
if (obj == null || obj.ToString() == string.Empty)
{
lstSheetColName.Add("列" + (i + ));
}
else
{
lstSheetColName.Add(obj.ToString());
}
}
return lstSheetColName;
} /// <summary>
/// 根据Sheet表名称,获取sheet的所有列的名称
/// </summary>
/// <param name="SheetName">Sheet表的名称</param>
/// <returns> List字符串集合 列名称 </returns>
public List<string> GetSheetColName(string files, string SheetName)
{
ISheet sheet = GetExcelsheet(files, SheetName);
//表头
IRow header = sheet.GetRow(sheet.FirstRowNum);
List<string> lstSheetColName = new List<string>();
for (int i = ; i < header.LastCellNum; i++)
{
object obj = GetValueType(header.GetCell(i));
if (obj == null || obj.ToString() == string.Empty)
{
lstSheetColName.Add("列" + (i + ));
}
else
{
lstSheetColName.Add(obj.ToString());
}
}
return lstSheetColName;
}
#endregion =====================获取特定的sheet的所有列的名称==================== /// <summary>
/// 获取单元格类型
/// </summary>
/// <param name="cell"></param>
/// <returns></returns>
private static object GetValueType(ICell cell)
{
if (cell == null)
return null;
switch (cell.CellType)
{
case CellType.Blank: //BLANK:
return null;
case CellType.Boolean: //BOOLEAN:
return cell.BooleanCellValue;
case CellType.Numeric: //NUMERIC:
return cell.NumericCellValue;
case CellType.String: //STRING:
return cell.StringCellValue;
case CellType.Error: //ERROR:
return cell.ErrorCellValue;
case CellType.Formula: //FORMULA:
default:
return "=" + cell.CellFormula;
}
}
}
NPOI 读取Excel文件的更多相关文章
- asp.net 使用NPOI读取excel文件
asp.net 使用NPOI读取excel文件内容 NPOI下载地址:NPOI public class ExcelHelper { /// <summary> /// 读取Excel文件 ...
- NPOI读取excel文件导出数据, 而此时文件正在打开中抛异常怎么办
项目中需要用到一些数值表格, 方便起见都是用excel来的. 而如果excel正打开中, 直接使用npoi制作的工具来导出数据的话, 在这一行将会异常: workbook = new XSSFWork ...
- NPOI读取Excel文件
public class ExcelOperator { public static List<DataTable> Read(string fileName) { List<Dat ...
- C#利用NPOI操作Excel文件
NPOI作为开源免费的组件,功能强大,可用来读写Excel(兼容xls和xlsx两种版本).Word.PPT文件.可是要让我们记住所有的操作,这便有点困难了,至此,总结一些在开发中常用的针对Excel ...
- 使用NPOI读取Excel表格内容并进行修改
前言 网上使用NPOI读取Excel文件的例子现在也不少,本文就是参考网上大神们的例子进行修改以适应自己需求的. 参考博文 http://www.cnblogs.com/restran/p/38894 ...
- c# .Net :Excel NPOI导入导出操作教程之读取Excel文件信息及输出
c# .Net :Excel NPOI导入导出操作教程之读取Excel文件信息及输出 using NPOI.HSSF.UserModel;using NPOI.SS.UserModel;using S ...
- 读取Excel文件的两种方法比较 以及用NPOI写入Excel
1. 采用NPOI方式,只需引用NPOI.dll,但目前最高只能到2.4.0版. 缺点:只支持.xls,不支持.xlsx格式.github上的2.4.1版支持.xlsx,但总提示缺ICSharpCod ...
- 读取Excel文件的两种方法
第一种方法:传统方法,采用OleDB读取EXCEL文件, 优点:写法简单,缺点:服务器必须安有此组件才能用,不推荐使用 private DataSet GetConnect_DataSet2(stri ...
- NPOI读取Excel,导入数据到Excel练习01
NPOI 2.2.0.0,初级读取导入Excel 1.读取Excel,将数据绑定到dgv上 private void button1_Click(object sender, EventArgs e) ...
随机推荐
- TextView文字描边实现
TextView文字描边实现 需求描述 文字显示在图片的上面,图片的内容是不确定了,为了防止文字与图片的颜色相近导致用户看不到或者看不清文字的问题,所以显示文字描边,避免问题. 实现 实现思想 使用T ...
- Day2:html和css
Day2:html和css 表格是一种常用的标签,表格结构,做到能够合并单元格. 表格的属性: 属性名 说明 border 设置表格的边框 cellspacing 设置单元格与单元格边框之间的空白间距 ...
- Python学习笔记【第十四篇】:Python网络编程二黏包问题、socketserver、验证合法性
TCP/IP网络通讯粘包问题 案例:模拟执行shell命令,服务器返回相应的类容.发送指令的客户端容错率暂无考虑,按照正确的指令发送即可. 服务端代码 # -*- coding: utf- -*- # ...
- Kali学习笔记15:防火墙识别、负载均衡识别、WAF识别
防火墙简单的识别方式: 如图: 可以简单明了看出:发送SYN不回应,发送ACK回RST可以说明开启过滤等等 基于这个原理,我们可以写一个脚本来对防火墙来探测和识别: #!/usr/bin/python ...
- 卷积神经网络CNN的原理(三)---代码解析
卷积神经网络在几个主流的神经网络开源架构上面都有实现,我这里不是想实现一个自己的架构,主要是通过分析一个最简单的卷积神经网络实现代码,来达到进一步的加深理解卷积神经网络的目的. 笔者在github上找 ...
- 全网最详细的如何在谷歌浏览器里正确下载并安装Postman【一款功能强大的网页调试与发送网页HTTP请求的Chrome插件】(图文详解)
不多说,直接上干货! 想必,玩过Java Web的你,肯定是对于http post和get等请求测试的过程记忆犹新吧. Postman的安装方法分好几种,主要分为两种安装模式介绍: (1)chrome ...
- [Android 泥水匠] Android基础 之一:浅谈Android架构到HelloWorld案例的剖析
作者:泥沙砖瓦浆木匠网站:http://blog.csdn.net/jeffli1993个人签名:打算起手不凡写出鸿篇巨作的人,往往坚持不了完成第一章节. 交流QQ群:[编程之美 365234583] ...
- Nacos发布0.5.0版本,轻松玩转动态 DNS 服务
阿里巴巴微服务开源项目Nacos于近期发布v0.5.0版本,该版本主要包括了DNS-basedService Discovery,对Java 11的支持,持续优化Nacos产品用户体验,更深度的与Sp ...
- Mybatis的原理相关
今天看了一篇有关Mybatis非常好的文章,顺便写了一下学习心得. 原文地址:https://blog.csdn.net/u010349169/article/details/40422941 一.M ...
- 深入MySQL复制(二):基于GTID复制
相比传统的MySQL复制,gtid复制无论是配置还是维护都要轻松的多.本文对gtid复制稍作介绍. MySQL基于GTID复制官方手册:https://dev.mysql.com/doc/refman ...