这两天快要评教了,所以要往数据库中导入数据,导入好几万条数据,这可是头疼啊,幸亏有咱们的导入功能。这两天对导入功能进行了一点点的改进。
面对这么多的数据难免往数据库中导入的时候有纰漏,没有提示是个麻烦的事情啊。后来跟小伙伴们商量一下,如果有错误数据则返回错误列表,好知道哪行出错了。对客户端进行了一点点的改进。
#region 批量导入数据——宋笑 2015年5月18日19:46:59
/// <summary>
/// 批量导入数据——宋笑 2015年5月18日19:46:59
/// </summary>
/// <returns></returns>
public ActionResult ImportCourse()
{
#region 文件验证以及上传到指定文件夹 Client端
HttpPostedFileBase file = Request.Files["files"];
string strFileName;
string strSavePath;
string ClientPath = AppDomain.CurrentDomain.BaseDirectory + "File\\UpFile\\";
string strPaperId = "1";
//这个是Client端的文件保存路径
if (file == null || file.ContentLength <= 0)
{
ViewBag.error = "文件不能为空";
return View();
}
else
{
string strFilename = Path.GetFileName(file.FileName);
int intFilesize = file.ContentLength;//获取上传文件的大小单位为字节byte
string fileEx = System.IO.Path.GetExtension(strFilename);//获取上传文件的扩展名
string strNoFileName = System.IO.Path.GetFileNameWithoutExtension(strFilename);//获取无扩展名的文件名
int Maxsize = 4000 * 1024;//定义上传文件的最大空间大小为4M
string FileType = ".xls,.xlsx";//定义上传文件的类型字符串
strFileName = strNoFileName + DateTime.Now.ToString("yyyyMMddhhmmss") + fileEx;
if (!FileType.Contains(fileEx))
{
ViewBag.error = "文件类型不对,只能导入xls和xlsx格式的文件";
//return View();
}
if (intFilesize >= Maxsize)
{
ViewBag.error = "上传文件超过4M,不能上传";
//return View();
}
strSavePath = Path.Combine(ClientPath, strFileName);
file.SaveAs(strSavePath);
}
#endregion
#region 将Client端上传的文件 上传到Server端
FileUploadMessage myFileMessage = new FileUploadMessage();
string strDataFileName = file.FileName;
myFileMessage.FileName = strDataFileName;//文件名
string CientPathName = ClientPath + strFileName;
using (FileStream fs = System.IO.File.OpenRead(CientPathName))
{
myFileMessage.FileData = fs;
try
{
_evalService.UploadFileMethod(myFileMessage);
}
catch { }
//关闭流
fs.Close();
}
#endregion
//返回的错误列表的表头。
string[] HeadName = { "课程编码", "课程名称", "课程类型", "课程性质", "是否排课", "学时", "学分", "层次", "机构类型", "学生总人数", "拼音", "操作员", "错误原因" };
if (_evalService.ServiceReadFile(strDataFileName, strPaperId)==null)
{
//如果导入的数据都是对的,则返回到界面。
_evalService.ServiceReadFile(strDataFileName, strPaperId);
return RedirectToAction("BasicCourseManager", "BasicCourse");
}
else
{
//如果返回的数据有错误,则返回错误列表。
DataTable table= _evalService.ServiceReadFile(strDataFileName, strPaperId)[0];
return File(Export.ExportManager.ExportExcel(table, HeadName), "application/vnd.ms-excel", "课程导入错误列表" + ".xls");
}
}
#endregion
把错误的数据返回到了错误列表,如图:
看起来是不是很高大上啊!不过导入这块儿还有一个问题就是,只能导入.xls文件,还有待改进!每一次改进都是一次进步!