public class ImportExcel
{
public static DataTable GetExcelDataTable(string filePath)
{
IWorkbook Workbook;
DataTable table = new DataTable();
try
{
using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
//XSSFWorkbook 适用XLSX格式,HSSFWorkbook 适用XLS格式
string fileExt = Path.GetExtension(filePath).ToLower();
if (fileExt == ".xls")
{
Workbook = new HSSFWorkbook(fileStream);
}
else if (fileExt == ".xlsx")
{
Workbook = new XSSFWorkbook(fileStream);
}
else
{
Workbook = null;
}
}
}
catch (Exception ex)
{
throw ex;
}
//定位在第一个sheet
ISheet sheet = Workbook.GetSheetAt(0);
//第一行为标题行
IRow headerRow = sheet.GetRow(0);
int cellCount = headerRow.LastCellNum;
int rowCount = sheet.LastRowNum;
//循环添加标题列
for (int i = headerRow.FirstCellNum; i < cellCount; i++)
{
DataColumn column = new DataColumn(headerRow.GetCell(i).StringCellValue);
table.Columns.Add(column);
}
//数据
for (int i = (sheet.FirstRowNum + 1); i <= rowCount; i++)
{
IRow row = sheet.GetRow(i);
DataRow dataRow = table.NewRow();
if (row != null)
{
for (int j = row.FirstCellNum; j < cellCount; j++)
{
if (row.GetCell(j) != null)
{
dataRow[j] = GetCellValue(row.GetCell(j));
}
}
}
table.Rows.Add(dataRow);
}
return table;
}
private static string GetCellValue(ICell cell)
{
if (cell == null)
{
return string.Empty;
}
switch (cell.CellType)
{
case CellType.Blank:
return string.Empty;
case CellType.Boolean:
return cell.BooleanCellValue.ToString();
case CellType.Error:
return cell.ErrorCellValue.ToString();
case CellType.Numeric:
case CellType.Unknown:
default:
return cell.ToString();
case CellType.String:
return cell.StringCellValue;
case CellType.Formula:
try
{
HSSFFormulaEvaluator e = new HSSFFormulaEvaluator(cell.Sheet.Workbook);
e.EvaluateInCell(cell);
return cell.ToString();
}
catch
{
return cell.NumericCellValue.ToString();
}
}
}
///
/// 大数据插入
///
/// 目标库连接
/// 目标表
/// 来源数据
public static void SqlBulkCopyByDatatable(string connectionString, string TableName, DataTable dtSelect)
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
using (SqlBulkCopy sqlbulkcopy = new SqlBulkCopy(connectionString, SqlBulkCopyOptions.UseInternalTransaction))
{
try
{
sqlbulkcopy.DestinationTableName = TableName;
sqlbulkcopy.BatchSize = 20000;
sqlbulkcopy.BulkCopyTimeout = 0;//不限时间
for (int i = 0; i < dtSelect.Columns.Count; i++)
{
sqlbulkcopy.ColumnMappings.Add(dtSelect.Columns[i].ColumnName, dtSelect.Columns[i].ColumnName);
}
sqlbulkcopy.WriteToServer(dtSelect);
}
catch (System.Exception ex)
{
throw ex;
}
}
}
}
public static void RemoveEmpty(DataTable dt)
{
List<DataRow> removelist = new List<DataRow>();
for (int i = 0; i < dt.Rows.Count; i++)
{
bool IsNull = true;
for (int j = 0; j < dt.Columns.Count; j++)
{
if (!string.IsNullOrEmpty(dt.Rows[i][j].ToString().Trim()))
{
IsNull = false;
}
}
if (IsNull)
{
removelist.Add(dt.Rows[i]);
}
}
for (int i = 0; i < removelist.Count; i++)
{
dt.Rows.Remove(removelist[i]);
}
}
}
说明:有关学籍对象的信息可查看本人之前的文章:ASP.NET MVC+EasyUi 分页显示数据表格 对应的Add方法可查看本人之前的文章:ASP.NET MVC+EasyUi 对数据表格进行增加,批量删除,修改操作
///
/// 导入
///
///
///
[HttpPost]
public int Import(HttpPostedFileBase file)
{
var fileName = file.FileName;
var filePath = Server.MapPath(string.Format("~/{0}", "Files"));
string path = Path.Combine(filePath, fileName);
file.SaveAs(path);
//从NPOI读取到的Excel的数据
DataTable excelTable = new DataTable();
excelTable = ImportExcel.GetExcelDataTable(path);
ImportExcel.RemoveEmpty(excelTable);
int result = 0;
foreach (DataRow dataRow in excelTable.Rows)
{
XJ xj = new XJ();
xj.xh = dataRow["xh"].ToString();
bool flag = xjService.FindByXh(xj.xh);
//判断该学号的学籍信息是否存在,若不存在则添加
if (!flag)
{
xj.xm = dataRow["xm"].ToString();
xj.xbm = Convert.ToInt32(dataRow["xbm"]);
xj.nj = dataRow["nj"].ToString();
xj.rxrq = Convert.ToDateTime(dataRow["rxrq"]);
xj.yxsh = dataRow["yxsh"].ToString();
xj.dsbh = dataRow["dsbh"].ToString();
xj.zydm = dataRow["zydm"].ToString();
xj.xslb = dataRow["xslb"].ToString();
result+=xjService.Add(xj);
}
}
return result;
}