前言
开始用的是OleDb读取表中数据,就是把表当成Access数据库通过sql读取,但是由于我的表结构特殊,经过尝试发现要完成我的要求比较复杂,所以改用了NPOI
NPOI用起来还算比较灵活可以很方便的操作Excel,确定啊就是需要引入4M的dll库,使得程序看起来比较庞大
下载引入NPOI(下载很慢请耐心等待多试两次)
推荐使用nuget下载添加引用.
也可在线下载地址:https://www.nuget.org/packages/NPOI/2.4.1
想了想还是提供下下载地址把(包含NPOI.2.4.1和SharpZipLib支持库):https://www.lanzous.com/i6935yh
将表中的数据读取到DataTable中
///
/// 从表中读取指定列填充到datatable中
///
/// 被读取的excel文件路径
/// 将读取到的数据封装成datatable返回
public static DataTable ExcelToDataTable(string filePath)
{
DataTable dataTable = null;
FileStream fs = null;
DataRow dataRow = null;
IWorkbook workbook = null;
ISheet sheet = null;
IRow row = null;
ICell cell = null;
try
{
#region excel后缀版本判断
fs = File.OpenRead(filePath);
// 2007版本
if (filePath.IndexOf(".xlsx") > 0)
workbook = new XSSFWorkbook(fs);
// 2003版本
else if (filePath.IndexOf(".xls") > 0)
workbook = new HSSFWorkbook(fs);
#endregion
//判断excel文件是否存在
if (workbook != null)
{
sheet = workbook.GetSheetAt(0);//读取第一个sheet,当然也可以循环读取每个sheet
dataTable = new DataTable();//创建datatable对象用来存储得到的数据
//判断excel表中是否存在表
if (sheet != null)
{
int rowCount = sheet.LastRowNum;//获取表中数据总行数
//如果行数大于0 在执行读取操作
if (rowCount > 0)
{
//构建datatable的列 (这里也可以循环读取表中的列自动创建)
dataTable.Columns.Add("编号", Type.GetType("System.Int32"));
dataTable.Columns[0].AutoIncrement = true;//设置自增列
dataTable.Columns[0].AutoIncrementSeed = 1;//起始值
dataTable.Columns[0].AutoIncrementStep = 1; //步长
dataTable.Columns.Add("姓名", Type.GetType("System.String"));
dataTable.Columns.Add("星期一", Type.GetType("System.String"));
//填充行 (因为i我表中的数据有标题从第四行才是我想要的数据,所以开始下标是4)
for (int i = 4; i <= rowCount; i++)
{
row = sheet.GetRow(i);//获取表中的第i行
if (row == null) continue;//如果行中没有数据就跳过
dataRow = dataTable.NewRow();//在datatable中创建一个新行
//向datatable行中的每一个单元格中填充读取到的数据
//因为datatable的第一列被我设置成了自增列所以这里直接从第二列开始填充
for (int j = 1; j < 3; j++)
{
cell = row.GetCell(j + 2);//获取上边从表中得到的行中的第j+2个单元格,这个自己该
//判断单元格是否为空,如果为空就把单元格设置内容填充为空,防止报错
if (cell == null)
{
dataRow[j] = "";
}
//如果不为空就判断格式,对单元格内容进行格式修改
else
{
#region 单元格格式判断
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 == 14 || format == 31 || format == 57 || format == 58)
dataRow[j] = cell.DateCellValue;
else
dataRow[j] = cell.NumericCellValue;
break;
case CellType.String:
dataRow[j] = cell.StringCellValue;
break;
}
#endregion
}
}
dataTable.Rows.Add(dataRow);//将上边填充好的行对象,添加到datatabale中
}
}
}
}
return dataTable;
}
catch (Exception e)
{
MessageBox.Show(e.Message);
if (fs != null)
{
fs.Close();
}
return null;
}
}