Mvc Excel导入加事务加导出

 

导出

public FileResult Input()
{
DataTable dt = new DataTable("dd");
using (SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=IOT1706B;Integrated Security=True"))
{
SqlDataAdapter sda = new SqlDataAdapter("select TypeName,Pid from IOTType", conn);
sda.Fill(dt);
}
//创建工作薄
IWorkbook workbook = new HSSFWorkbook();
//创建工作表
ISheet sheet = workbook.CreateSheet("sheet0");
//创建表头行
IRow cells = sheet.CreateRow(0);
//写入表头
for (int i = 0; i < dt.Columns.Count; i++)
{
//创建列赋值
cells.CreateCell(i).SetCellValue(dt.Columns[i].ColumnName);
}
//写入表内容
for (int i = 1; i <= dt.Rows.Count; i++)
{
//创建行
IRow cells1 = sheet.CreateRow(i);
for (int j = 0; j < dt.Columns.Count; j++)
{
//创建列赋值
cells1.CreateCell(j).SetCellValue(dt.Rows[i - 1][j].ToString());
}
}
//导出
using (MemoryStream stream = new MemoryStream())
{
workbook.Write(stream);
return File(stream.GetBuffer(), "applocation/excel", "导出.xls");
}

}

 

导入加事务

public int Post()
{
HttpFileCollection fileBase = HttpContext.Current.Request.Files;
if (Path.GetExtension(fileBase[0].FileName)==".xls")
{
try
{
Stream stream = fileBase[0].InputStream;
IWorkbook workbook = new HSSFWorkbook(stream);
ISheet sheet = workbook.GetSheetAt(0);
DataTable dt = new DataTable("d");
IRow cells = sheet.GetRow(0);
foreach (ICell item in cells)
{
dt.Columns.Add(item.StringCellValue);
}

for (int i = 1; i <= sheet.LastRowNum; i++)
{
IRow cells1 = sheet.GetRow(i);
int j = 0;
DataRow dr = dt.NewRow();
foreach (ICell item in cells1)
{
switch (item.CellType)
{
case CellType.Numeric:
dr[item.ColumnIndex] = item.NumericCellValue;
break;
case CellType.String:
dr[item.ColumnIndex] = item.StringCellValue;
break;

case CellType.Boolean:
dr[item.ColumnIndex] = item.BooleanCellValue;
break;
default:
dr[j] = "";
break;
}
}
dt.Rows.Add(dr);
}
using (SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=IOT1706B;Integrated Security=True"))
{
conn.Open();
SqlTransaction tran = conn.BeginTransaction();
SqlCommand cmd = conn.CreateCommand();
cmd.Transaction = tran;
try
{
int n = 0;

foreach (DataRow item in dt.Rows)
{
cmd.CommandText = "insert into IOTType values(";
foreach (var ii in item.ItemArray)
{
cmd.CommandText += $"'{ii}',";
}
cmd.CommandText= cmd.CommandText.TrimEnd(',');
cmd.CommandText += $")";
n += cmd.ExecuteNonQuery();

}
tran.Commit();
conn.Close();
return n;
}
catch (Exception)
{
tran.Rollback();
return 0;
throw;
}
}

}
catch (Exception)
{

throw;

}


}
else
{
return -1;
}
}
posted @ 2019-12-23 19:46  噜啦啦0001  阅读(275)  评论(0编辑  收藏  举报