namespace MvcApplication1.Controllers
{
public class ExcelController : Controller
{
//
// GET: /Excel/
public ActionResult Index()
{
return View();
}
/// <summary>
/// Excel上传部分
/// 导入 Import
/// </summary>
/// <param name="Exc"></param>
/// <returns></returns>
[HttpPost]
public ActionResult outExcel(HttpPostedFileBase Exc)
{
#region /// 上传部分
//如果当前的网站目录为E:wwwroot 应用程序虚拟目录为E:wwwrootcompany 浏览的页面路径为E:wwwrootcompany
ewsshow.asp
//在show.asp页面中使用
//Server.MapPath("./") 返回路径为:E:wwwrootcompany
ews
//Server.MapPath("/") 返回路径为:E:wwwroot
//Server.MapPath("../") 返回路径为:E:wwwrootcompany
//Server.MapPath("~/") 返回路径为:E:wwwrootcompany
string strfileName = Server.MapPath("/Word/"); //存储文件的地方
if (!Directory.Exists(strfileName)) //判断文件路径是否存在
{
Directory.CreateDirectory(strfileName);
}
string fName = Path.GetFileName(Exc.FileName); //获取文件名
Exc.SaveAs(strfileName + fName);
#endregion
#region /// Execl导入部分
//execl文件读取
Excelhelper exc = new Excelhelper();
DataTable dt = exc.ExcelToDS(strfileName + fName);
List<Student> ls = new List<Student>();
foreach (DataRow dr in dt.Rows)
{
Student student = new Student();
student.sno = dr[0].ToString();
student.name = dr[1].ToString();
student.age = dr[2].ToString();
student.sex = dr[3].ToString();
ls.Add(student);
}
#endregion
Session["Students"] = ls;
return View("index");
}
/// <summary>
/// 导出 export
/// </summary>
/// <returns></returns>
public ActionResult ExcInput()
{
#region /// 查询部分
List<Student> ls = Session["Students"] as List<Student>;
#endregion
Excelhelper exc = new Excelhelper();
//foreach (Student e in ls)
//{
// exc.ExcelToAdd("D:/studentDemo.xls", e);
//}
exc.ExcelToAdd("D:/studentDemo.xls", ls);
return View();
//课堂练习 使用NPOI 下载excel
}
//public FileResult aaa()
//{
// return Json(object);
//}
}
}