Excel数据导入___你hold住么(一)

        近期小编跟着团队一起开发ITOO3.0高校云平台项目,当中的收获是不言而喻滴,在项目中有个导入功能:导入学生信息;导入班级信息:导入教学楼信息等,在不知多少次的尝试之下,成功实现功能。

框架分析

将保存在Excel表格的信息导入到SQL数据表中

        详解一下

        -第一步:在MVC框架的Client端新建目录
Excel模板

        - 第二步:通过NPOI文件流(详细的专业名称不知道是叫啥。姑且称文件流)将保存在Client的Excel文件流传到WCF框架的Server端

        - 第三步:在Server端中,新建目录保存Excel模板的xml文件
这里写图片描写叙述
        Server端中的XML文件起到解析的作用,从而将Excel 中的数据插入Insert到数据表中


代码设计

        上传Excel到Server
* Controller

private readonly IUploadFile upLoadService1 = ServiceFactory.GetUploadFileService();
#region ImportFlowBatch()+批量导入流程-徐露-2015年7月8日10:39:02
///
/// 批量导入流程
///
///
public ActionResult ImportFlowBatch()
{
#region 文件验证以及上传到指定目录 Client端
HttpPostedFileBase file = Request.Files[“files”];
string strFileName;
string strSavePath;
string ClientPath = AppDomain.CurrentDomain.BaseDirectory + “FileUpFile”;
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
            {
                upLoadService1.UploadFileMethod(myFileMessage);
            }
            catch { }
            //关闭流
            fs.Close();
        }
        #endregion
        string[] HeadName = { "流程ID", "流程名称", "优先级", "是否启用(启用1。未启用0)", "流程Url", "时间戳", "是否删除" };

        //调用执行 写数据库
        if(upLoadService1.ServiceReadFile (strDataFileName ,strPaperId )==null) {

         return RedirectToAction("Index","ImportStudent");
        }
        else 
        {
            DataTable table = upLoadService1 .ServiceReadFile (strDataFileName ,strPaperId )[0];
            return File (Export .ExportManager .ExportExcel (table,HeadName ),"application/vnd.ms-excel", "流程导入错误列表" + ".xls");

        }           
    }
    #endregion

         *在Service中读取Excel文件,写入数据库
须要加的三个:IUploadFile(接口)、UploadFile(实现类)、以及ServiceFactory(工厂)
        篇幅限制,详细代码不再粘贴。小编会详细上传Demo,另行下载

        *XML配置
        针对每个导入的Excel都须要一个对应的XML配置文件,以便底层方法可以解析获取
        XML应统一放置在某一路径下,详细路径配置例如以下:

<appConfig>下加入节点
        <add key="ExcelImportXMLPath" value="Models/ImportConfigXML"/>
即将配置文件存放路径放在了Service层的Models/ImportConfigXML目录下。

命名:各系统可依据详细情况详细命名,调用方法时须要传入XML文件名称称

        详细XML配置可參考:

<?xml version="1.0" encoding="utf-8" ?>
<Excel name="导入流程模板">
  <Sheet name="流程" table="FreshFlowEntity" primaryKey="FlowID" pkType="guid">

    <Column name="流程名称" field="Name">
      <DataType>string</DataType>
      <ForeignKey isExist="false"></ForeignKey>
    </Column>
    <Column name="优先级" field="Sort" isNecessary="true">
      <DataType>int</DataType>
      <ForeignKey isExist="false"></ForeignKey>
    </Column>
    <Column name="是否启用(启用1,未启用0)" field="IsUse" isVerifyRepeat="false"  >
      <DataType>int</DataType>
      <ForeignKey isExist="false"></ForeignKey>
    </Column>
    <Column name="流程Url" field="Url" isVerifyRepeat="false">
      <DataType>string</DataType>
      <ForeignKey isExist="false"></ForeignKey>
    </Column>
    <Column name="时间戳" field="TimeSpan" isNecessary="false" isVerifyRepeat="false" >
      <DataType>DateTime</DataType>
      <ForeignKey isExist="false"></ForeignKey>
    </Column>
    <Column name="是否删除" field="IsDelete" isVerifyRepeat="false">
      <DataType>int</DataType>
      <ForeignKey isExist="false"></ForeignKey>
    </Column>
  </Sheet>
</Excel>

        以上就是做导入的基本流程,那是不是完善敲出代码就能正常执行呢,请见小编下文分析 link text

原文地址:https://www.cnblogs.com/gccbuaa/p/7073872.html