Esempio n. 1
0
        public PartialViewResult Index(HttpPostedFileBase fileexcel)
        {
            BanTinTuVan bantintuvan = new BanTinTuVan();

            if (fileexcel != null && fileexcel.ContentLength > 0)
            {
                try
                {
                    string name = ReadNameFile(fileexcel.FileName);
                    string path = "~/Files/somefiles/"; // path: đường dẫn lưu fileexcel tải lên
                    Path.Combine(HostingEnvironment.MapPath(path));
                    String pathOnServer = Path.Combine(path);
                    //var fullPath = Path.Combine(pathOnServer, Path.GetFileName(name));
                    var fullPath = Path.Combine(Server.MapPath(path),
                                                Path.GetFileName(name));
                    fileexcel.SaveAs(fullPath);    // lua file vào server
                    string    url   = path + name; // url: đường dẫn lưu file excel trên server
                    ReadExcel excel = new ReadExcel();
                    url = Path.Combine(HostingEnvironment.MapPath(url));
                    List <DataTable> table = excel.makeDataTableFromSheetName(url, excel.MySheet(url));
                    bantintuvan = excel.BanTinTuVanExcel(table);
                }
                catch (Exception) { }
                return(PartialView("TuVan_ViewChung", bantintuvan));
            }
            return(PartialView());
        }
    /// <summary>
    /// 读取子弹配置列表
    /// </summary>
    /// <returns></returns>
    public static Dictionary <int, BulletProperty> ReadBulletProperty()
    {
        DataRowCollection dataLst = ReadExcel.GameReadExcel(ExcelPathConfigs.BULLET_ROPERTY_PATH);
        Dictionary <int, BulletProperty> bulletPropertyDict = new Dictionary <int, BulletProperty>();

        if (dataLst == null)
        {
            Debug.Log("ReadBulletProperty is failed! DataRowCollection obj is null!");
            return(bulletPropertyDict);
        }
        for (int i = 1; i < dataLst.Count; i++)
        {
            BulletProperty data    = new BulletProperty();
            DataRow        excelst = dataLst[i];
            if (excelst[0].ToString() == "" && excelst[1].ToString() == "")
            {
                continue;
            }

            data.Id         = int.Parse(excelst[0].ToString());  //子弹id
            data.BulletName = excelst[1].ToString();             //子弹名称

            data.Damage      = int.Parse(excelst[2].ToString()); //子弹伤害
            data.MaxDamage   = int.Parse(excelst[3].ToString()); //子弹伤害
            data.PrefabsPath = excelst[4].ToString();            //子弹路径

            bulletPropertyDict.Add(data.Id, data);
        }
        return(bulletPropertyDict);
    }
Esempio n. 3
0
        static void Main(string[] args)
        {
            string           excelFileName = System.AppDomain.CurrentDomain.BaseDirectory + "Test.xls";
            CreateWriteExcel cwExcel       = new CreateWriteExcel();

            cwExcel.TestWriteExcel(excelFileName);



            ReadExcel rExcel = new ReadExcel();

            // 测试读取 前面创建 的 Excel 文件.
            rExcel.TestRead(excelFileName, String.Empty, true);


            // 测试读取 标题不在 第一行的情况。
            rExcel.TestRead("Report.xls", "A4:C100", true);


            // 测试读取 没有标题 的情况。
            rExcel.TestRead("Test2.xls", String.Empty, false);



            // 注意1:下面这种情况, 第一行需要是空白的
            // 测试读取 没有标题  且数据不在第一行的情况。
            // 注意2:当 Excel 中, 某一列,内容一直是数字的, 然后突然变字符了,会发生无法读取到该行的字符数据的问题。
            rExcel.TestRead("Report2.xls", "A4:C100", true);


            Console.ReadLine();
        }
Esempio n. 4
0
    public void ParseMonsterData()
    {
        List <string> monstersStringData = ReadExcel.GameReadExcel(monsterPath);

        for (int i = 0; i < monstersStringData.Count; i++)
        {
            string[] monsterStringData = monstersStringData[i].Split('|');
            Monster  monster           = new Monster();
            if (monsterStringData.Length != 0)
            {
                monster.m_ID                    = int.Parse(monsterStringData[0]);
                monster.m_name                  = monsterStringData[1];
                monster.m_HP                    = float.Parse(monsterStringData[2]);
                monster.m_Attack_Damage         = float.Parse(monsterStringData[3]);
                monster.m_Attack_Speed          = float.Parse(monsterStringData[4]);
                monster.m_Defence               = float.Parse(monsterStringData[5]);
                monster.m_Kongfu_ID             = int.Parse(monsterStringData[6]);
                monster.m_Kongfu_Lvl            = int.Parse(monsterStringData[7]);
                monster.m_Internal_Strength     = int.Parse(monsterStringData[8]);
                monster.m_Internal_Strength_Lvl = int.Parse(monsterStringData[9]);
            }
            if (monster != null)
            {
                monsterList.Add(monster);
            }
        }
        Debug.Log("[MonsterModule][ParseMonsterData] monsterList = " + monsterList.Count);
    }
Esempio n. 5
0
        public ActionResult ChooseKnowledge()
        {
            string today = time;

            Puzzle[]    pList = pc.PuzzleList.Where(p => p.uploadtime == today).ToArray();
            Knowledge[] kList;
            User        u  = (User)Session["User"];
            ReadExcel   re = new ReadExcel();

            for (int i = 0; i < pList.Length; i++)
            {
                Puzzle p         = pList[i];
                string knowledge = (string)Request.Form[(string)("knowledge1st-" + i)] + "-" + (string)Request.Form[(string)("knowledge2nd-" + i)];
                p.puzzle_knowledge = knowledge;
                p.uploader         = u.user_account;
                pc.PuzzleList.Attach(p);
                pc.Entry(p).State = System.Data.EntityState.Modified;
            }
            pc.SaveChanges();
            kList = re.readKowledge(filePath, pList.Length, pList);
            for (int i = 0; i < kList.Length; i++)
            {
                Knowledge k = kList[i];
                Score     s = sc.ScoreList.Where(score => score.stu_id == k.stu_id).FirstOrDefault();
                if (s != null)
                {
                    k.stu_class = s.stu_class;
                    k.uploader  = u.user_account;
                    kc.KnowledgeList.Add(k);
                }
                //kc.Entry(k).State = System.Data.EntityState.Modified;
            }
            kc.SaveChanges();
            return(RedirectToAction("Index", "Head"));
        }
Esempio n. 6
0
        private void Begin_Click(object sender, EventArgs e)
        {
            Stopwatch sw = new Stopwatch();

            sw.Start();
            var fullUri = string.Empty;

            if (string.IsNullOrWhiteSpace(PathBox.Text))
            {
                fullUri = string.Format($"{Environment.CurrentDirectory}\\Data\\OD.xlsx");
            }
            else
            {
                fullUri = PathBox.Text;
            }
            messageBox.Text += string.Format($"开始计算,文件路径为{fullUri}\r\n");
            var result = ReadExcel.LuDuan(fullUri);

            result = result.OrderBy(l => l.No).ToList();
            var luduans = ReadExcel.LuduanAndPoint(result, fullUri);

            messageBox.Text += string.Format($"导入路段完成,路段数{luduans.Count}\r\n");
            var nodes = ReadExcel.Nodes(fullUri);

            messageBox.Text += string.Format($"导入节点完成,节点数{nodes.Count}\r\n");
            var ods = ReadExcel.OD(fullUri);

            messageBox.Text += string.Format($"导入OD完成,OD对数{ods.Count}\r\n");
            ReadExcel.Varia(fullUri);
            messageBox.Text += string.Format($"导入参数完成\t\n");
            messageBox.Text += string.Format($"{nameof(Varias.LuJingCount)}:{Varias.LuJingCount}\r\n");
            foreach (var od in ods)
            {
                od.LuJings = GenarateLuJing.GetAllPath(od, luduans, nodes);
                foreach (var lujing in od.LuJings) //添加路段所在路径信息
                {
                    foreach (var luduan in lujing.LuDuans)
                    {
                        if (luduan.No != 0)
                        {
                            if (luduans.NumOf(luduan.No).At == null)
                            {
                                luduans.NumOf(luduan.No).At = new List <LuJing>();
                            }

                            if (!luduans.NumOf(luduan.No).At.Any(l => l.start.No == lujing.Nodes.First().No&& l.end.No == lujing.Nodes.Last().No))
                            {
                                luduans.NumOf(luduan.No).At.Add(lujing);
                            }
                        }
                    }
                }
            }
            var uri = string.Format($"{Environment.CurrentDirectory}");

            Iteration.Run(ods, luduans, nodes, uri);
            sw.Stop();
            messageBox.Text += string.Format($"任务完成!耗时{sw.ElapsedMilliseconds / 1000}秒");
        }
Esempio n. 7
0
 private void BrowseFolderButtonOpenExcel()
 {
     FormSetup(folderBrowserDialog1.SelectedPath);
     TestCases = ReadExcel.ReadAllTestCasesFromExcel(openFileDialog.FileName);
     TestCases.Sort();
     CheckForExistingCodeAndShowAlert();
     AddTestCaseToFormAndShow(false);
 }
Esempio n. 8
0
    /// <summary>
    /// 呼叫對話腳本
    /// </summary>
    /// <param name="page">頁碼(代碼)</param>
    public void Call(string page, bool isTransparent)
    {
        dialog.AddRange(ReadExcel.Read("Dialog", page, 0, -1));
        speaker.AddRange(ReadExcel.Read("Dialog", page, 1, -1));
        align.AddRange(ReadExcel.Read("Dialog", page, 2, -1));

        StartCoroutine(ProcessDialog(isTransparent));
    }
 protected override void Seed(MaintenanceScheduleContext context)
 {
     using (EFUnitOfWork work = new EFUnitOfWork("ProbLoc"))
     {
         ReadExcel read = new ReadExcel();
         read.Read(work);
     }
 }
Esempio n. 10
0
        public string BulkInsert(string fileName)
        {
            ReadExcel excel = new ReadExcel(fileName);

            excel.ReadFile();

            return("Ok");
        }
Esempio n. 11
0
        public void ODs()
        {
            var fullUri = string.Format($"{Environment.CurrentDirectory}\\OD.xlsx");
            var result  = ReadExcel.OD(fullUri);

            result = result.OrderBy(od => od.Start).ThenBy(od => od.End).ToList();

            Assert.IsTrue(result.Count > 0);
        }
Esempio n. 12
0
        public ActionResult UploadExcel(FormCollection formCollection)
        {
            WorldRefExcelDataModel worldExcelModel = new WorldRefExcelDataModel();
            string retStatus = "";

            try
            {
                worldExcelModel.IsOrganization = formCollection["Organization"] == null ? false : true;
                worldExcelModel.IsCustomer     = formCollection["Customer"] == null ? false : true;
                worldExcelModel.IsProject      = formCollection["Project"] == null ? false : true;
                worldExcelModel.IsType         = formCollection["Type"] == null ? false : true;
                worldExcelModel.IsYear         = formCollection["Year"] == null ? false : true;
                worldExcelModel.IsStatus       = formCollection["Status"] == null ? false : true;
                //   worldExcelModel.IsCountry = formCollection["Country"] == null ? false : true;
                // worldExcelModel.IsEmail = formCollection["Email"] == null ? false : true;
                worldExcelModel.userid = Convert.ToInt32(Request.Cookies["UserId"].Value);

                ReadExcel readExcel = new ReadExcel();

                string path      = string.Empty;
                string filename  = string.Empty;
                string SavePath  = string.Empty;
                string Extension = string.Empty;
                foreach (string upload in Request.Files)
                {
                    SavePath = Guid.NewGuid().ToString();
                    path     = AppDomain.CurrentDomain.BaseDirectory + "uploads/";
                    filename = Path.GetFileName(Request.Files[upload].FileName);

                    Extension = Path.GetExtension(Request.Files[upload].FileName);

                    if (Extension.ToLower() != ".xls" && Extension.ToLower() != ".xlsx")
                    {
                        TempData.Clear();
                        TempData.Add("ErrorMessage", "Please Upload Correct format.Please Download the Format");
                        return(RedirectToAction("UploadExcel"));
                    }

                    Request.Files[upload].SaveAs(Path.Combine(path, SavePath + Extension));
                }
                readExcel.ExcelPath       = Path.Combine(path, SavePath + Extension);
                worldExcelModel.ExcelPath = Path.Combine(SavePath + Extension).ToString();
                worldExcelModel.ExcelName = filename;
                retStatus = readExcel.ReadDataFromExcel();
                readExcel.AddData(worldExcelModel);

                TempData.Clear();
                TempData.Add("ErrorMessage", "Thank you for taking a step forward to glorifying yourself in WorlRef Map");
            }
            catch (Exception ex)
            {
                TempData.Clear();
                TempData.Add("ErrorMessage", ex.Message.ToString());//"Please Upload Correct format.Please Download the Format");
                return(RedirectToAction("UploadExcel"));
            }
            return(RedirectToAction("UploadExcel"));
        }
Esempio n. 13
0
        public void Nodes()
        {
            var fullUri = string.Format($"{Environment.CurrentDirectory}\\OD.xlsx");
            var result  = ReadExcel.Nodes(fullUri);

            result = result.OrderBy(od => od.No).ToList();

            Assert.AreEqual(50, result.Count);
        }
        public ActionResult UploadExcel(FormCollection formCollection)
        {
            WorldRefExcelDataModel worldExcelModel = new WorldRefExcelDataModel();
            string retStatus = "";
            try
            {
                worldExcelModel.IsOrganization = formCollection["Organization"] == null ? false : true;
                worldExcelModel.IsCustomer = formCollection["Customer"] == null ? false : true;
                worldExcelModel.IsProject = formCollection["Project"] == null ? false : true;
                worldExcelModel.IsType = formCollection["Type"] == null ? false : true;
                worldExcelModel.IsYear = formCollection["Year"] == null ? false : true;
                worldExcelModel.IsStatus = formCollection["Status"] == null ? false : true;
                //   worldExcelModel.IsCountry = formCollection["Country"] == null ? false : true;
                // worldExcelModel.IsEmail = formCollection["Email"] == null ? false : true;
                worldExcelModel.userid = Convert.ToInt32(Request.Cookies["UserId"].Value);

                ReadExcel readExcel = new ReadExcel();

                string path = string.Empty;
                string filename = string.Empty;
                string SavePath = string.Empty;
                string Extension = string.Empty;
                foreach (string upload in Request.Files)
                {
                    SavePath = Guid.NewGuid().ToString();
                    path = AppDomain.CurrentDomain.BaseDirectory + "uploads/";
                    filename = Path.GetFileName(Request.Files[upload].FileName);

                    Extension = Path.GetExtension(Request.Files[upload].FileName);

                    if (Extension.ToLower() != ".xls" && Extension.ToLower() != ".xlsx")
                    {
                        TempData.Clear();
                        TempData.Add("ErrorMessage", "Please Upload Correct format.Please Download the Format");
                        return RedirectToAction("UploadExcel");
                    }

                    Request.Files[upload].SaveAs(Path.Combine(path, SavePath + Extension));
                }
                readExcel.ExcelPath = Path.Combine(path, SavePath + Extension);
                worldExcelModel.ExcelPath = Path.Combine(SavePath + Extension).ToString();
                worldExcelModel.ExcelName = filename;
                retStatus = readExcel.ReadDataFromExcel();
                readExcel.AddData(worldExcelModel);

                TempData.Clear();
                TempData.Add("ErrorMessage", "Thank you for taking a step forward to glorifying yourself in WorlRef Map");
            }
            catch (Exception ex)
            {
                TempData.Clear();
                TempData.Add("ErrorMessage", ex.Message.ToString());//"Please Upload Correct format.Please Download the Format");
                return RedirectToAction("UploadExcel");
            }
            return RedirectToAction("UploadExcel");
        }
Esempio n. 15
0
    private void CreatTaskHotspotGroupJsonExample()
    {
        Debug.Log("SaveJson");
        //List<T> -> Json ( 例 : List<Enemy> )
        List <TaskHotspotGroup> tasks = ReadExcel.ReadTaskHotspotGroup(m_excelPath);
        //string str = JsonUtility.ToJson(tasks); // 输出 : { }
        string str = JsonUtility.ToJson(new Serialization <TaskHotspotGroup>(tasks));

        File.WriteAllText(Application.streamingAssetsPath + m_jsonListPath, str);
        Debug.Log(str);
    }
Esempio n. 16
0
        public IActionResult ExportRelease(int idRelease, string codRelease, [FromServices] VivoDAO vivoDAO)
        {
            ReadExcel readExcel = new ReadExcel(_hostingEnvironment);

            List <TestesVivo> testesVivo = vivoDAO.ListaTestesVivo(idRelease);

            string       url          = string.Format("{0}://{1}/{2}", Request.Scheme, Request.Host, $"{codRelease}.xlsx");
            MemoryStream memoryStream = readExcel.DownloadTestesVivo(testesVivo, codRelease, url);

            return(File(memoryStream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", $"{codRelease}.xlsx"));
        }
 /// <summary>
 /// 武器库数据读取和相关函数操作操作,读取武器库ExcelData
 /// </summary>
 public void ReadWeaponPropertyByExecl()
 {
     WeaponProPertyDic = ReadExcel.ReadWeaponProperty();
     foreach (WeaponProperty data in WeaponProPertyDic.Values)
     {
         if (data.WeaponName == "手雷")
         {
             GrenadesId = data.Id;                           //保存手雷的ID
         }
         WeaponQueue.Add(data.Id);
     }
 }
Esempio n. 18
0
    public void Read(string path)
    {
        if (questionDic == null)
        {
            questionDic = new Dictionary <int, Question>();
        }
        questionDic.Clear();

        ReadExcel.Read(path).ForEach(x =>
        {
            questionDic.Add(x.id, x);
        });
        OnLoadEndAction.Invoke();
    }
Esempio n. 19
0
        public IActionResult CadastrarReleaseVivo(VivoRelease vivoRelease, IFormFile excel, int qtdTestes, [FromServices] VivoDAO vivoDAO)
        {
            ViewBag.Erro = false;
            if (excel is null)
            {
                ModelState.AddModelError("", "Arquivo da planilha não encontrado!");
            }

            if (qtdTestes == 0)
            {
                ModelState.AddModelError("", "Quantidade de testes é obrigatório!");
            }

            if (!ModelState.IsValid)
            {
                return(View());
            }

            //Criando Release
            List <VivoRelease> releases = vivoDAO.GetListReleaseVivo();

            if (!releases.Any(r => r.CodRelease == vivoRelease.CodRelease))
            {
                bool insert = vivoDAO.InsertReleaseVivo(vivoRelease);
                if (!insert)
                {
                    ModelState.AddModelError("", "Erro ao cadastratar release! Informe o Administrador do site!");
                }
            }
            else
            {
                ModelState.AddModelError("CodRelease", "CRQ já cadastrada!");
                return(View());
            }
            //

            //Lendo Planilha
            releases = vivoDAO.GetListReleaseVivo();
            VivoRelease releaseCadastrada = releases.Where(r => r.CodRelease == vivoRelease.CodRelease).First();

            ReadExcel         readExcel = new ReadExcel(_hostingEnvironment);
            List <TestesVivo> listTeste = readExcel.VivoPlanTestes(excel, qtdTestes, releaseCadastrada.CodRelease, releaseCadastrada.IdRelease);

            vivoDAO.InsertTestesVivo(listTeste);
            //

            ViewBag.Erro = true;
            return(View());
        }
Esempio n. 20
0
    /// <summary>
    ///     set data type auto
    /// </summary>
    /// <param name="cell"></param>
    /// <param name="data"></param>
    /// <param name="myWindow"></param>
    /// <returns></returns>
    private static DataInfo SetDataType(ICell cell, DataInfo data, ReadExcel myWindow)
    {
        // Debug.Log("<color=red>"+myWindow.excelFile.filePath+cell.Sheet.SheetName + ".type." + data.titleName+"</color>");
        if (cell.CellType != CellType.Unknown && cell.CellType != CellType.Blank)
        {
            if (EditorPrefs.GetInt(myWindow.excelFile.filePath + cell.Sheet.SheetName + ".type." + data.titleName, 20) != 20)
            {
                data.type = (ValueType)EditorPrefs.GetInt(myWindow.excelFile.filePath + cell.Sheet.SheetName + ".type." + data.titleName);
                return(data);
            }
            data.type = ValueType.STRING;
            EditorPrefs.SetInt(myWindow.excelFile.filePath + cell.Sheet.SheetName + ".type." + data.titleName, (int)ValueType.STRING);

            try
            {
                // Debug.Log("int:" + cell.ToString());
                int.Parse(cell.ToString());
                data.type = ValueType.INT;
                EditorPrefs.SetInt(myWindow.excelFile.filePath + cell.Sheet.SheetName + ".type." + data.titleName, (int)ValueType.INT);
                if (data.isArray)
                {
                    try
                    {
                        var datas = cell.ToString().Split(',');
                        int.Parse(datas[0]);
                        data.type = ValueType.INT;
                        EditorPrefs.SetInt(myWindow.excelFile.filePath + cell.Sheet.SheetName + ".type." + data.titleName, (int)ValueType.INT);
                    }
                    catch
                    {
                    }
                }
            }
            catch
            {
            }

            try
            {
                bool.Parse(cell.ToString());
                data.type = ValueType.BOOL;
                EditorPrefs.SetInt(myWindow.excelFile.filePath + cell.Sheet.SheetName + ".type." + data.titleName, (int)ValueType.BOOL);
            }
            catch
            {
            }
        }
        return(data);
    }
Esempio n. 21
0
        public ActionResult Index(ReadExcel readExcel)
        {
            if (ModelState.IsValid)
            {
                //string path = Server.MapPath("~/Content/Upload" + readExcel.File.FileName);
                string folder = Server.MapPath("~/Content/Upload");
                string file   = Path.GetFileName(readExcel.File.FileName);
                string path   = Path.Combine(folder, file);
                readExcel.File.SaveAs(path);

                string          excelConnectionString = @"Provider='Microsoft.ACE.OLEDB.12.0';Data Source='" + path + "';Extended Properties='Excel 12.0 Xml;IMEX=1'";
                OleDbConnection excelConnection       = new OleDbConnection(excelConnectionString);

                //Sheet Name
                excelConnection.Open();
                string tableName = excelConnection.GetSchema("Tables").Rows[0]["TABLE_NAME"].ToString();
                excelConnection.Close();
                //End

                OleDbCommand cmd = new OleDbCommand("SELECT * FROM [" + tableName + "]", excelConnection);

                excelConnection.Open();

                OleDbDataReader dbReader = cmd.ExecuteReader();

                EntityConnectionStringBuilder entityConnectionStringBuilder = new EntityConnectionStringBuilder(ConfigurationManager.ConnectionStrings["SampleDatabaseEntities"].ConnectionString);
                string connectionString = entityConnectionStringBuilder.ProviderConnectionString;

                SqlBulkCopy sqlBulk = new SqlBulkCopy(connectionString);

                //Give destination table name
                sqlBulk.DestinationTableName = "Sale";

                //Mappings
                sqlBulk.ColumnMappings.Add("Date", "AddedOn");
                sqlBulk.ColumnMappings.Add("Region", "Region");
                sqlBulk.ColumnMappings.Add("Person", "Person");
                sqlBulk.ColumnMappings.Add("Item", "Item");
                sqlBulk.ColumnMappings.Add("Units", "Units");
                sqlBulk.ColumnMappings.Add("Unit Cost", "UnitCost");
                sqlBulk.ColumnMappings.Add("Total", "Total");

                sqlBulk.WriteToServer(dbReader);
                excelConnection.Close();

                ViewBag.Result = "Successfully Imported";
            }
            return(View());
        }
Esempio n. 22
0
        public bool Upload(HttpPostedFileBase file)
        {
            MemoryStream target = new MemoryStream();

            file.InputStream.CopyTo(target);
            byte[]   data     = target.ToArray();
            HttpFile httpFile = new HttpFile(file.FileName, file.ContentType, data);

            DataSet dataSet = ReadExcel.ToDataSet(httpFile.Buffer);

            DataTable resultDt = dataSet.Tables[0];

            List <Student> students = new List <Student>();

            students = Convertor.ConvertToList <Student>(resultDt);

            return(true);
        }
        public void GetAllPath()
        {
            var od = new OD()
            {
                Start = 3,
                End   = 5
            };
            var fullUri = string.Format($"{Environment.CurrentDirectory}\\OD.xlsx");
            var result  = ReadExcel.LuDuan(fullUri);

            result = result.OrderBy(l => l.No).ToList();
            var luduans = ReadExcel.LuduanAndPoint(result, fullUri);
            var nodes   = ReadExcel.Nodes(fullUri);

            var result2 = GenarateLuJing.GetAllPath(od, luduans, nodes);

            Assert.AreEqual(1, 1);
        }
Esempio n. 24
0
        static void Main(string[] args)
        {
            Stopwatch stopWatch = new Stopwatch();

            stopWatch.Start();
            String file        = @"C:\Users\Uther\Desktop\РАФ\УССО_30_01.xlsx";
            String path2       = @"C:\Users\Uther\Desktop\РАФ\NotValid.xlsx";
            bool   InDiffLists = false;

            var dataSet = ReadExcel.GetDataSetFromExcelFile(file);

            Console.WriteLine(string.Format("reading file: {0}", file));
            Console.WriteLine(string.Format("coloums: {0}", dataSet.Tables[0].Columns.Count));
            Console.WriteLine(string.Format("rows: {0}", dataSet.Tables[0].Rows.Count));

            var lists = DataIntoList.IntoList(dataSet);

            var NotValidList = lists.Item2;

            FileStream objFileStrm = File.Create(path2);

            objFileStrm.Close();

            WriteExcel.SetDataSetFromExcelFile(InDiffLists, NotValidList, path2);//NotValid into Excel

            var RowObjInfoListJSON = DataIntoList.IntoJList(lists.Item1);
            //var json = JsonConvert.SerializeObject(RowObjInfoListJSON, Formatting.Indented);
            int count = lists.Item1.Count;

            JSON.ToJSON(count, RowObjInfoListJSON);
            stopWatch.Stop();

            TimeSpan ts = stopWatch.Elapsed;
            // Format and display the TimeSpan value.
            string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
                                               ts.Hours, ts.Minutes, ts.Seconds,
                                               ts.Milliseconds / 10);

            Console.WriteLine("RunTime " + elapsedTime);

            Console.WriteLine(lists.Item1.Count);

            Console.ReadKey();
        }
Esempio n. 25
0
        private void btnGetGoalDiff_Click(object sender, EventArgs e)
        {
            try
            {
                string    result            = string.Empty;
                ReadExcel readExcel         = new ReadExcel();
                string    csv_file_path     = ConfigurationManager.AppSettings["FilePath"];
                DataTable dt                = readExcel.ReadCsvFile(csv_file_path);
                var       datarows          = dt.AsEnumerable().Where(row => row.ItemArray.All(o => !string.IsNullOrEmpty(o.ToString())));
                var       matchScoreDetails = datarows.Select(datarow =>
                                                              new MatchScoreDetails()
                {
                    Team         = datarow[(int)Enums.ScoreExcelFileColumnIndex.Team].ToString(),
                    TotalMatches = Convert.ToInt32(datarow[(int)Enums.ScoreExcelFileColumnIndex.TotalMatches]),
                    Won          = Convert.ToInt32(datarow[(int)Enums.ScoreExcelFileColumnIndex.Won]),
                    Loss         = Convert.ToInt32(datarow[(int)Enums.ScoreExcelFileColumnIndex.Loss]),
                    Draw         = Convert.ToInt32(datarow[(int)Enums.ScoreExcelFileColumnIndex.Draw]),
                    GoalFor      = Convert.ToInt32(datarow[(int)Enums.ScoreExcelFileColumnIndex.GoalFor]),
                    GoalAgainst  = Convert.ToInt32(datarow[(int)Enums.ScoreExcelFileColumnIndex.GoalAgainst]),
                    points       = Convert.ToInt32(datarow[(int)Enums.ScoreExcelFileColumnIndex.Points]),
                }).ToList();
                bool isValid = validateStructure(matchScoreDetails);

                if (isValid)
                {
                    var lowestScore = matchScoreDetails.Where(c => (c.GoalFor - c.GoalAgainst) >= 0).Min(c => (c.GoalFor - c.GoalAgainst));
                    var winner      = (from k in matchScoreDetails where ((k.GoalFor - k.GoalAgainst) == lowestScore) select k.Team).FirstOrDefault();
                    result = Constants.WinnerTeam + winner.ToString();
                }
                else
                {
                    result = Constants.ErrorMessage;
                }
                lblMessage.Text = result;
            }
            catch (CustomException)
            {
                throw new CustomException(string.Format(Constants.ErrorMessage));
            }
            catch (Exception ex)
            {
                lblMessage.Text = ex.Message;
            }
        }
Esempio n. 26
0
        private void GenerateCSV(IEnumerable <ReportContact> reportContacts, string fileName)
        {
            if (reportContacts.IsAny())
            {
                Log.Informational("Request received for generating CSV with filename as : " + fileName);
                string location = _jobConfig.NeverBounceCsvFiles;
                location += fileName.Replace(".xls", ".csv").Replace(".xlsx", ".csv").Replace(".xml", ".csv");

                DataTable table = ConvertToDataTable(reportContacts);
                ReadExcel ex    = new ReadExcel();
                byte[]    bytes = ex.ConvertDataSetToCSV(table, string.Empty);
                File.WriteAllBytes(location, bytes);
                Log.Informational("CSV generated successfully");
            }
            else
            {
                throw new UnsupportedOperationException("Couldn't find contacts with email for filename : " + fileName);
            }
        }
Esempio n. 27
0
        /// <summary>
        /// HieuTM: Upload file, phân tích trả về mẫu dữ liệu.
        /// </summary>
        /// <returns></returns>
        public PartialViewResult UploadExcel()
        {
            LogDb.WriteLogInfo("HieuTM", "UploadExcel", "TuVanController", "Vao Upload");
            BanTinTuVan bttv = null;

            try
            {
                LogDb.WriteLogInfo("HieuTM", "UploadExcel", "TuVanController", "file count: " + Request.Files.Count.ToString());
                string linkSaveServer = "";
                for (int i = 0; i < Request.Files.Count; i++)
                {
                    string directoryPath = Path.Combine((Server.MapPath("~/Files/tuvan/")));
                    var    file          = Request.Files[i];
                    string filename      = file.FileName;

                    if (!System.IO.Directory.Exists(directoryPath))
                    {
                        System.IO.Directory.CreateDirectory(directoryPath);
                    }

                    string newname = Lib.Security.CurrentUserName + "_" + DateTime.Now.ToString("yyyyMMdd_HHmmss") + "_" + Path.GetFileName(file.FileName);
                    linkSaveServer   = Path.Combine(Server.MapPath("~/Files/tuvan/"), newname);
                    ViewBag.LinkFile = linkSaveServer;
                    file.SaveAs(linkSaveServer);
                    ReadExcel        excel = new ReadExcel();
                    List <DataTable> table = excel.makeDataTableFromSheetName(linkSaveServer, excel.MySheet(linkSaveServer));

                    bttv = table.Count == 0 ? null : excel.BanTinTuVanExcel(table);
                    if (bttv != null)
                    {
                        bttv.Link = @"Files/tuvan/" + newname;
                    }
                }
            }
            catch (Exception ex)
            {
                bttv = null;
                LogDb.WriteLogInfo("HieuTM", "UploadExcel", "TuVanController", "Error: " + ex.Message);
                LogDb.WriteLogError("HieuTM", "UploadExcel", "TuVanController", ex);
            }
            return(PartialView("TuVan_All_Par", bttv));
        }
    //读取武器配置列表
    public static Dictionary <int, WeaponProperty> ReadWeaponProperty()
    {
        DataRowCollection dataLst = ReadExcel.GameReadExcel(ExcelPathConfigs.WEAPONP_ROPERTY_PATH);
        Dictionary <int, WeaponProperty> weaponPropertyDict = new Dictionary <int, WeaponProperty>();

        if (dataLst == null)
        {
            Debug.Log("ReadWeaponProperty is failed! DataRowCollection obj is null!");
            return(weaponPropertyDict);
        }
        for (int i = 1; i < dataLst.Count; i++)
        {
            WeaponProperty data    = new WeaponProperty();
            DataRow        excelst = dataLst[i];
            if (excelst[0].ToString() == "" && excelst[1].ToString() == "")
            {
                continue;
            }

            data.Id         = int.Parse(excelst[0].ToString());               //武器id
            data.WeaponName = excelst[1].ToString();                          //武器名称

            data.ShootRange             = int.Parse(excelst[2].ToString());   //射程
            data.MaxShootRange          = int.Parse(excelst[3].ToString());   //最大射程
            data.ATK                    = float.Parse(excelst[4].ToString()); //攻击力
            data.FireRate               = float.Parse(excelst[5].ToString()); //射速
            data.ShootSpeed             = float.Parse(excelst[6].ToString()); //子弹射击速度
            data.MinAccumulateForce     = float.Parse(excelst[7].ToString()); //蓄力最小数
            data.MaxAccumulateForce     = float.Parse(excelst[8].ToString()); //蓄力最大数
            data.MaxAccumulateForceTime = float.Parse(excelst[9].ToString()); //蓄力最大限制时间
            data.MinConsumeEnergy       = int.Parse(excelst[10].ToString());  //最小能量消耗数值
            data.MaxConsumeEnergy       = int.Parse(excelst[11].ToString());  //最大能量消耗数值
            data.HP = int.Parse(excelst[12].ToString());                      //武器的子弹数

            data.PrefabsPath = excelst[13].ToString();                        //预置体路
            data.BulletId    = int.Parse(excelst[14].ToString());             //子弹Id
            weaponPropertyDict.Add(data.Id, data);
        }
        return(weaponPropertyDict);
    }
        public static XElement GetSearchXml(string xmlName)
        {
            List <string> list      = ReadExcel.GetDirectoryFiles("~/Views/Shared/SearchDialogXml/");
            XElement      targetXml = null;

            foreach (var item in list)
            {
                XElement        settingXml = XElement.Load(item);
                List <XElement> excelList  = settingXml.Elements("searchDialog").Where(e => e.Attribute("name").Value.Equals(xmlName)).ToList();
                if (excelList.Count > 0)
                {
                    targetXml = excelList.First();
                    break;
                }
            }
            if (targetXml == null)
            {
                throw new Exception("未配置此xml文本!");
            }
            return(targetXml);
            //List<XElement> fieldList = targetXml.Element("ColumnList").Elements("column").ToList();
        }
Esempio n. 30
0
        public ActionResult CommonImportExcel_Templet(string xmlName)
        {
            var           Excel_Templet_Url = "";
            List <string> list      = ReadExcel.GetDirectoryFiles("~/Views/Shared/ImportExcelXml/");
            XElement      targetXml = null;

            foreach (var item in list)
            {
                XElement        settingXml = XElement.Load(item);
                List <XElement> excelList  = settingXml.Elements("Excel").Where(e => e.Attribute("name").Value.Equals(xmlName)).ToList();
                if (excelList.Count > 0)
                {
                    targetXml         = excelList.First();
                    Excel_Templet_Url = ReadXml.getXmlElementValue(targetXml, "ExcelTempletURL");
                    if (!string.IsNullOrWhiteSpace(Excel_Templet_Url))
                    {
                        Excel_Templet_Url = Excel_Templet_Url.Replace("\n", "").Replace(" ", "").Trim();
                    }
                }
            }
            return(Content(Excel_Templet_Url));
        }
Esempio n. 31
0
        public void crearModelo()
        {
            ReadExcel   objExcel;
            INodeObject nodoInicio            = null;
            INodeObject nodoFin               = null;
            INodeObject nodoInicioMapa        = null;
            Path        objPath               = new Path();
            int         distanciaIni          = 0;
            int         distanciaNodoAnterior = 0;

            objExcel = new ReadExcel();
            var listPuntos = objExcel.readCSV("coordenadasmapalite.csv", true);

            foreach (var item in listPuntos)
            {
                TransferNode tn = new TransferNode(item.id, item.ejeX, item.ejeY);
                nodoFin = tn.getTransferNode();


                if (nodoInicioMapa == null)
                {
                    nodoInicioMapa = nodoFin;
                    distanciaIni   = item.distancia;
                }

                if (nodoInicio != null)
                {
                    objPath.idpath = item.id;
                    objPath.Enlazar(nodoInicio, nodoFin);
                    objPath.setDistancia(distanciaNodoAnterior);
                }
                nodoInicio            = nodoFin;
                distanciaNodoAnterior = item.distancia;
            }

            objPath.idpath = 1;
            objPath.Enlazar(nodoFin, nodoInicioMapa);
            objPath.setDistancia(distanciaNodoAnterior);
        }