View
@model BSServer.Models.PagerIndexModel
@{
ViewBag.Title = "站点信息一览";
}
///
/// 站点控制器
///
public class SiteManageController : Controller
{
///
/// 导入Excel方法
///
///
///
public ActionResult ImportSiteInfo()
{
try
{
#region 文件上传
//文件路径
string path = string.Empty;
//文件名称
string filename=string.Empty;
//文件与路径
string filePath = string.Empty;
foreach (string upload in Request.Files)
{
//判断当前上传控件是否为空
if (Request.Files.Count > 0)
{
//判断当前上传控件是否为空
if (Request.Files[upload] != null && Request.Files[upload].ContentLength > 0)
//当前工程路径与上传文件夹
path = AppDomain.CurrentDomain.BaseDirectory + "uploadSite/";
//文件名称
filename = Path.GetFileName(Request.Files[upload].FileName);
//文件与路径
filePath = Path.Combine(path, filename);
//保存在当前工程文件夹
Request.Files[upload].SaveAs(filePath);
}
}
#endregion
#region 导入文件
//判断是否为空导入
if (string.IsNullOrEmpty(path))
{
return RedirectToAction("SiteInfoList", "SiteManage");
}
else
{
//判断当前文件是否为Excel
if (!filename.Contains("xls"))
return RedirectToAction("SiteInfoList", "SiteManage");
}
ImportExcel importEx = new ImportExcel();
//获取Excel中的数据
DataTable dtSite = importEx.ExcelDataSource(filePath, "Sheet1").Tables[0];
//添加到数据库
foreach (DataRow item in dtSite.Rows)
{
Site s = new Site()
{
Name = item["Name"].ToString().Trim(),
LocalID = int.Parse(item["LocalID"].ToString().Trim())
};
//判断当前站点是否存在
if (!string.IsNullOrEmpty(SiteManageBusiness.GetSiteNameByName(s.Name)))
continue;
SiteManageBusiness.AddSiteInfo(s);
}
#endregion
return RedirectToAction("SiteInfoList", "SiteManage", new { import = 1 });
}
catch (Exception ex)
{
return RedirectToAction("SystemError", "SysException", new { ExInfo = "堆栈消息:" + ex.StackTrace + "\n\n 异常消息:" + ex.Message });
}
}
}
Common
public class ImportExcel
{
///
/// 获取Excel数据方法
///
/// 文件路径
/// sheet名称
///
public DataSet ExcelDataSource(string filepath, string sheetname)
{
try
{
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filepath + ";Extended Properties=Excel 8.0;";
OleDbConnection conn = new OleDbConnection(strConn);
OleDbDataAdapter oada = new OleDbDataAdapter("select * from [" + sheetname + "$]", strConn);
DataSet ds = new DataSet();
oada.Fill(ds);
return ds;
}
catch (Exception ex)
{
throw ex;
}
}
}