Mvc导入

[HttpPost]
public void Import()
{
//获取文件

HttpPostedFileBase fileBase = Request.Files["file"];

if(fileBase==null)
{
  Response.Write("");
}
//转数据流
Stream stream = fileBase.InputStream;
IWorkbook workbook = null;

if (Path.GetExtension(fileBase.FileName).ToLower().Equals(".xls"))
{
  workbook = new HSSFWorkbook(stream);
}
//获取sheet
ISheet sheet = workbook.GetSheetAt(0);
//获取头
IRow row = sheet.GetRow(0);
//定义datatable
DataTable dt = new DataTable();
foreach (ICell item in row.Cells)
{
//循环添加表头
  dt.Columns.Add(item.StringCellValue);
}
for (int i = 0; i <= sheet.LastRowNum; i++)
{
  DataRow dr = dt.NewRow();
  for (int j = 0; j < sheet.GetRow(i).Cells.Count; j++)
{

CellType cellType = sheet.GetRow(i).Cells[j].CellType;
int index = sheet.GetRow(i).Cells[j].ColumnIndex;
switch (cellType)
{
  case CellType.Numeric:dr[index]=sheet.GetRow(i).Cells[j].NumericCellValue;
  break;
  case CellType.String:
  dr[index] = sheet.GetRow(i).Cells[j].StringCellValue;
  break;
  case CellType.Boolean:
  dr[index] = sheet.GetRow(i).Cells[j].BooleanCellValue;
  break;
  }
}
  dt.Rows.Add(dr);
}


//sql拼接
try
{
dt.Columns.RemoveAt(0);
foreach (DataRow item in dt.Rows)
{
  string sql = $"inserrt into mess values(";
  foreach (object it in item.ItemArray)
  {
  sql += $"'{it}',";
  }
  sql = sql.TrimEnd(',');
  sql += ")";
  DB.ExecuteNonQuery(sql);
  }
}
catch (Exception)
{

throw;
}
}

//前台

<form action="/Default/Import" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="file">
<input type="submit" name="name" class="btn btn-success btn-sm" value="导入">
</form>

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值