excel文件导入数据库
[HttpPost]
public ActionResult TestExcel(FormCollection form)
{
HttpPostedFileBase file = Request.Files[0];
string path = Server.MapPath("\\Models");
path += "\\" + file.FileName;
file.SaveAs(path);
ImportExcelFile(path);
return View();
}
/// <summary>
/// 根据Excel列类型获取列的值
/// </summary>
/// <param name="cell">Excel列</param>
/// <returns></returns>
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();
}
}
}
/// <summary>
/// Excel导入
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
public DataTable ImportExcelFile(string filePath)
{
HSSFWorkbook hssfworkbook;
try
{
using (FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
hssfworkbook = new HSSFWorkbook(file);
}
}
catch (Exception e)
{
throw e;
}
ISheet sheet = hssfworkbook.GetSheetAt(3);
DataTable table = new DataTable();
IRow headerRow = sheet.GetRow(0);//第一行为标题行
int cellCount = headerRow.LastCellNum;//LastCellNum = PhysicalNumberOfCells
int rowCount = sheet.LastRowNum - 2;
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 + 4); 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);
}
using (SqlBulkCopy abc = new SqlBulkCopy(SqlConnectionFactory.Connection))
{
abc.BatchSize = table.Rows.Count;
abc.BulkCopyTimeout = 11;
abc.DestinationTableName = "ExcelTable";
for (int i = 0; i < table.Columns.Count; i++)
{
abc.ColumnMappings.Add(table.Columns[i].ColumnName, i);
}
abc.WriteToServer(table);
}
return table;
}
public string ExcelSelect()
{
using (SqlConnection con = SqlConnectionFactory.Connection)
{
string sql = "select Tnumber, Tname, Depter, Bdate, Beonduty, GetoffWork, BeondutyTwo, GetoffWorkTwo, Belate, Leaver, Absenceoftime, Total, BText from ExcelTable";
var list = con.Query(sql);
return JsonConvert.SerializeObject(list);
}
}
<form action="/Home/TestExcel" enctype="multipart/form-data" method="post">
<text>选择上传文件:(工作表名为“Sheet1”,“电脑号”在A1单元格。)</text>
<input name="file" type="file" id="file" />
<input type="submit" name="Upload" value="批量导入第一批电脑派位名册" />
</form>