博 之 文

以 拼 搏 设 计 梦 想 , 以 恒 心 编 程 明 天
  首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

excel下拉导出模板代码 nopi来自文件下载

Posted on 2015-05-20 11:07  IsNull_Soft  阅读(253)  评论(0)    收藏  举报
public void ExportUser(int userId, out string pathExcel)
        {
            string path = EVE.Library.Config.WebConfig.UploadPath + "/InputModul/";
            var userModel = new UserService().Get(userId);
            var departments = departmentDAL.Entities.Where(p => p.CompanyID == userModel.CompanyID);

            string[] genderArray = new string[] { "", "" };

            int itemIndex = 0;
            string[] departArray = new string[departments.Count()];
            departments.ForEach(item =>
            {
                departArray[itemIndex] = item.Name;
                itemIndex++;
            });

            var roles = roleDAL.Entities.Where(p => p.CompanyID == userModel.CompanyID);
            string[] roleArray = new string[roles.Count()];
            int itemRole = 0;
            roles.ForEach(item =>
            {
                roleArray[itemRole] = item.Name;
                itemRole++;
            });

            DirectoryInfo dirInfo = new DirectoryInfo(path + @"/Temp/");
            FileInfo[] files = dirInfo.GetFiles();
            foreach (FileInfo file in files) { file.Delete(); }

            //要操作的excel文件路径
            FileStream fsStream = File.OpenRead(path + @"userInputDataModul.xls");
            HSSFWorkbook workbook = new HSSFWorkbook(fsStream);

            var userInputSheet = workbook.GetSheet(workbook.GetSheetName(0));
            CellRangeAddressList dRegions = new CellRangeAddressList(1, 8888, 0, 0);
            DVConstraint dConstraint = DVConstraint.CreateExplicitListConstraint(departArray);
            HSSFDataValidation dDataValidate = new HSSFDataValidation(dRegions, dConstraint);
            userInputSheet.AddValidationData(dDataValidate);

            CellRangeAddressList gRegions = new CellRangeAddressList(1, 8888, 3, 3);
            DVConstraint gConstraint = DVConstraint.CreateExplicitListConstraint(genderArray);
            HSSFDataValidation gDataValidate = new HSSFDataValidation(gRegions, gConstraint);
            userInputSheet.AddValidationData(gDataValidate);

            CellRangeAddressList rRegions = new CellRangeAddressList(1, 8888, 8, 8);
            DVConstraint rConstraint = DVConstraint.CreateExplicitListConstraint(roleArray);
            HSSFDataValidation rDataValidate = new HSSFDataValidation(rRegions, rConstraint);
            userInputSheet.AddValidationData(rDataValidate);

            pathExcel = path + @"/Temp/userInputDataModul_" + Guid.NewGuid().ToStr() + ".xls";
            //把编辑过后的工作薄重新保存为excel文件
            FileStream fs2 = File.Create(pathExcel);

            workbook.Write(fs2);
            fs2.Close();
        }