protected virtual void Init() { csvFile = Resources.Load <TextAsset>("Texts/" + name) as TextAsset; csvArray = CSVHelper.SplitCsv(csvFile.text); DebugLog(); }
int ExportDataGrid(Stream stream, UnicontaBaseEntity[] corasauBaseEntity, Dictionary <string, int> mappedItems) { Type RecordType; if (corasauBaseEntity.Length > 0) { RecordType = corasauBaseEntity[0].GetType(); } else { return(0); } var Props = new List <PropertyInfo>(); var Headers = new List <string>(); var sortedItems = (from l in mappedItems where l.Value > 0 orderby l.Value ascending select l).ToList(); foreach (var strKey in sortedItems) { var pInfo = RecordType.GetProperty(strKey.Key); if (pInfo != null) { Headers.Add(UtilFunctions.GetDisplayNameFromPropertyInfo(pInfo)); Props.Add(pInfo); } } int cnt = 0; #if !SILVERLIGHT var writer = new StreamWriter(stream, Encoding.Default); cnt = CSVHelper.ExportDataGridToExcel(stream, Headers, corasauBaseEntity, Props, spreadSheet, ".xlsx", "Intrastat"); writer.Flush(); #endif return(cnt); }
private static void cruzaDeputadosCandidatos() { // Coletado com coletarDeputadosApi() var deputados = Directory .GetFiles(@"B:\Temp\api\deputados\", "*.json") .Select(f => JsonConvert.DeserializeObject <Deputado>(File.ReadAllText(f))) .ToDictionary(o => o.dados.cpf); // http://agencia.tse.jus.br/estatistica/sead/odsele/consulta_cand/consulta_cand_2020.zip -> Brasil.csv var arquivo = @"B:\Temp\consulta_cand_2020_BRASIL.csv"; using var fs = File.OpenRead(arquivo); var lines = CSVHelper.FileSplit(new StreamReader(fs, Encoding.UTF7)) .Skip(1); Console.WriteLine("Lendo candidatos"); foreach (var line in lines) { // [20] CPF var cpf = line[20]; if (deputados.ContainsKey(cpf)) { var deputado = deputados[cpf]; Console.WriteLine($"{deputado.dados.id:000000} {deputado.dados.cpf} {deputado.dados.nomeCivil} -> {line[12]}/{line[14]} [{line[28]}]"); string url = $"https://www.camara.leg.br/cota-parlamentar/sumarizado?nuDeputadoId={deputado.dados.id}&dataInicio=8/2020&dataFim=10/2020&despesa=&nomeHospede=&nomePassageiro=&nomeFornecedor=&cnpjFornecedor=&numDocumento=&sguf=&filtroNivel1=1&filtroNivel2=2&filtroNivel3=3"; var document = FetchHelper.FetchResourceDocument(new Uri(url), enableCaching: true); } } }
protected void btnExport_OnClick(object sender, EventArgs e) { try { var result = GetData(true); var headerList = new List <string>() { "序号", "退单号", "订单号", "预订人", "电话", "预定时间", "退单商品", "退款总额", "退单状态" }; var columnIndex = new List <int>() { 11, 2, 3, 4, 5, 6, 7, 8, 10 }; CSVHelper.DownloadAsSCV(Response, "退单管理", result.Tables[0], columnIndex, headerList); } catch (Exception) { } }
/// <summary> /// 从配置表读取方块和怪物的信息 /// </summary> public void InitData() { CSVHelper.Instance().ReadCSVFile("CubeConfig", (table) => { // 可以遍历整张表 foreach (CSVLine line in table) { Consts.cubeList.Add(new BaseCube(Int32.Parse(line["cubeId"]), line["cubeName"], line["imgUrl"], line["describe"], line["tag"])); } readFinishCube = true; readFinsh = readFinishCube && readFinishAilist; }); CSVHelper.Instance().ReadCSVFile("monsterConfig", (table) => { // 可以遍历整张表 foreach (CSVLine line in table) { Consts.AIList.Add(new AIInfo(Int32.Parse(line["aiid"]), line["aiName"], line["imgUrl"], Int32.Parse(line["patrolDistance"]), Int32.Parse(line["patrolSpeed"]), Int32.Parse(line["followDistance"]), float.Parse(line["followSpeed"]), float.Parse(line["attackDistance"]), Int32.Parse(line["jumpHeight"]), Int32.Parse(line["attackPower"]), Int32.Parse(line["hp"]), bool.Parse(line["isStepDeath"]), bool.Parse(line["isHurtBlock"]), bool.Parse(line["isBurstBlock"]), bool.Parse(line["isGravityBlock"]), bool.Parse(line["attackOtherAi"]), bool.Parse(line["attackBlock"]), Int32.Parse(line["fallDeathHeight"]), line["describe"], line["attack"], line["health"], line["speed"])); } readFinishAilist = true; readFinsh = readFinishCube && readFinishAilist; }); }
private void ok_Click(object sender, EventArgs e) { DataTable User_new = User.Copy(); if (username.Text == null || username.Text.Equals("")) { MessageBox.Show("用户名不能为空!"); return; } if (psw1.Text == null || psw1.Text.Equals("")) { MessageBox.Show("密码不能为空!"); return; } if (psw1.Text != psw2.Text) { MessageBox.Show("两次密码不一致!"); return; } DataRow newline = User.Rows[1]; int r = User_new.Rows.Count + 1; newline[0] = r.ToString(); newline[1] = username.Text; newline[2] = psw1.Text; newline[3] = "0"; User_new.Rows.Add(newline.ItemArray); CSVHelper.SaveCSV(User_new, path); MessageBox.Show("新增用户" + username.Text + "成功!"); this.Close(); }
public void ShouldAddDataToExistingCsvFile() { //Arrange var result = new ResultCollection <ResultItemCollection>(); result.AddItem("Witcher 3", new List <ResultItem> { new ResultItem { Name = "Product Name", Value = "Witcher 3" }, new ResultItem { Name = "Url", Value = "http://witcher.com" } }); result.AddItem("NBA 2k20", new List <ResultItem> { new ResultItem { Name = "Product Name", Value = "NBA 2k20" }, new ResultItem { Name = "Url", Value = "http://nba2k20.com" } }); var fileName = $"{Path.GetDirectoryName(TestContext.CurrentContext.TestDirectory)}/debug/MightyApeScrapper/export_add_row.csv"; //Act //Create the first CSV File CSVHelper.WriteObject(fileName, result); Assert.That(File.Exists(fileName)); }
public void ShouldWriteCsvColumns() { //Arrange var result = new ResultCollection <ResultItemCollection>(); result.AddItem("Witcher 3", new List <ResultItem> { new ResultItem { Name = "Product Name", Value = "Witcher 3" }, new ResultItem { Name = "Url", Value = "http://witcher.com" } }); result.AddItem("NBA 2k20", new List <ResultItem> { new ResultItem { Name = "Product Name", Value = "NBA 2k20" }, new ResultItem { Name = "Url", Value = "http://nba2k20.com" } }); var fileName = $"{Path.GetDirectoryName(TestContext.CurrentContext.TestDirectory)}/debug/MightyApeScrapper/export.csv"; //Act and Assert Assert.DoesNotThrow(() => CSVHelper.WriteObject(fileName, result)); Assert.That(File.Exists(fileName)); }
public IActionResult Save(IFormCollection collection) { User user = CollectionToUser(collection); try { DateTime dt = DateTime.Now; CSVHelper all = new CSVHelper("wwwroot/Registrazioni/Registrazioni_tutte.csv", ";", new string[] { "data", "nome", "cognome", "data_nascita", "via", "numero_civico", "citta", "nap", "telefono", "email", "sesso", "hobby", "professione" }); CSVHelper day = new CSVHelper(string.Format("wwwroot/Registrazioni/Registrazioni_{0}_{1}_{2}.csv", dt.Year, dt.Month, dt.Day), ";", new string[] { "data", "nome", "cognome", "data_nascita", "via", "numero_civico", "citta", "nap", "telefono", "email", "sesso", "hobby", "professione" }); string[] s = new string[] { dt.ToString(), user.FirstName, user.LastName, user.Birthday.ToString(), user.Address, user.CivicNumber, user.City, user.Nap.ToString(), user.PhoneNumber, user.Email, user.Gender, user.Hobby, user.Job }; all.Write(s); day.Write(s); return(RedirectToAction("", "ReadCheck")); } catch (Exception) { return(View("Index")); } }
private void LoadLevelTiles(TextAsset tiles, TextAsset prefabs) { string[] prefabDef = Regex.Split(prefabs.ToString(), "\r\n"); GameObject[] prefabObjects = new GameObject[prefabDef.Length]; for (int i = 0; i < prefabDef.Length; i++) { prefabObjects[i] = Resources.Load(PrefabFolder + prefabDef[i], typeof(GameObject)) as GameObject; } CSVHelper csv = new CSVHelper(tiles.ToString(), ","); int lineNum = 0; LevelX = 0; foreach (string[] line in csv) { int yCoordinate = (csv.Count - (lineNum + 1)) * GridSize; if (line.Length > LevelX) { LevelX = line.Length; } for (int i = 0; i < line.Length; i++) { if (line[i] != string.Empty) { GameObject newObject = GameObject.Instantiate(prefabObjects[int.Parse(line[i])]); newObject.transform.position = new Vector3(i * GridSize, yCoordinate, 1); newObject.transform.SetParent(LevelTilesParent, true); } } lineNum++; } LevelX *= 16; }
void Start() { gameObject.GetComponent <Rigidbody2D>().gravityScale = 0; string filename = ""; CSVHelper.Instance().ReadCSVFile("configuration", (table) => { // 可以遍历整张表 foreach (CSVLine line in table) { foreach (KeyValuePair <string, string> item in line) { Debug.Log(string.Format("item key = {0} item value = {1}", item.Key, item.Value)); } } //可以拿到表中任意一项数据 filename = table["1"]["name"]; //Debug.Log(filename); outPath = Application.dataPath + filename + ".csv"; stdDev1 = float.Parse(table["2"]["name"]); stdDev2 = float.Parse(table["3"]["name"]); stdDev3 = float.Parse(table["4"]["name"]); stdDev4 = float.Parse(table["5"]["name"]); stdDev5 = float.Parse(table["6"]["name"]); carspeedY = float.Parse(table["7"]["name"]); }); //每次启动客户端删除之前保存的Log if (File.Exists(outPath)) { File.Delete(outPath); } }
/// <summary> /// Parses the specified probability table. /// </summary> /// <typeparam name="T">Probability table key type</typeparam> /// <param name="fileName">Name of the file.</param> /// <param name="hasHeader">Indicates that probability file has a header line</param> /// <returns>Parsed probability table.</returns> public static ProbabilityTable <T> Parse <T>(string fileName, bool hasHeader) { var probabilities = CSVHelper.ReadAllRecords <ProbabilityRecord <T> >( fileName, hasHeader, typeof(ProbabilityRecordMap <T>)); return(new ProbabilityTable <T>(probabilities.ToDictionary(p => p.Value, p => p.Probability))); }
public static DataTable GetDataTableByFile(string filePath) { DataTable dt = new DataTable(); dt = CSVHelper.csv2dt(filePath, 0, dt); return(dt); }
public static string wirteDataTableToFile(DataTable dt, string fileName) { string fullPath = FileHelper.MapPath(fileName); CSVHelper.SaveCSV(dt, fullPath); return(fullPath); }
public static DataTable GetTestSource(string testPath) { DataTable dt = new DataTable(); dt = CSVHelper.csv2dt(testPath, 0, dt); return(dt); }
public static string CreateTrainData(string filePath, int count = 1) { try { DataTable dt = new DataTable(); dt = CSVHelper.csv2dt(filePath, 0, dt); dt.Columns.Remove("gpdm"); dt.Columns.Remove("mc"); dt.Columns.Add("mspj"); for (int i = 1; i < dt.Rows.Count - 1; i++) { dt.Rows[i]["mspj"] = dt.Rows[i - 1]["spj"]; } for (int i = 0; i < count; i++) { dt.Rows.RemoveAt(0); } string fullPath = FileHelper.MapPath("trainData.csv"); CSVHelper.SaveCSV(dt, fullPath); return(fullPath); } catch (Exception ex) { throw ex; } }
protected void btnExport_OnClick(object sender, EventArgs e) { try { var result = GetData(); if (result.Any() || result.Any()) { List <string> headerList = new List <string>() { "订单编号", "订单状态", "订单关闭日期", "预约人", "数量", "商品名称", "入住时间" , "离店时间", "商品单价", "总计" }; List <int> columnIndexList = new List <int>() { 3, 2, 11, 4, 5, 6, 7, 8, 9, 10 }; CSVHelper.DownloadAsSCV <OrderDetailDTO>(Response, "服务凭据查询", result, columnIndexList, headerList); } } catch { } }
private void weaponJudge() { judgeTimes.Clear(); int equipCount = 1; CSVHelper csv = CSVManager.getInstance().getCsvByName("equip"); for (int i = 0; i < equipCount; i++) { int times = csv.getIntDataByIDandTitle(1001, "decisionTime"); int property = csv.getIntDataByIDandTitle(1001, "propertyDecision"); int value = (int)attrData.toValue((AttributeData.AttrType)property); for (int n = 0; n < times; n++) { if (UnityEngine.Random.Range(0, 100) < value) { judgeTimes.Add(1); } else { judgeTimes.Add(0); } } } manager.showWeaponJudge(judgeTimes); actionType = UnitType.BATTLE_NONE; // 2秒后执行攻击 Invoke("setActionTypeToAttack", 2); }
static void getAllTextAndToLangCSV() { List <List <string> > csv_contents = new List <List <string> >(); Text[] texts = FindObjectsOfType <Text>(); for (int i = 0; i < texts.Length; i++) { Text text_temp = texts[i]; List <string> text_csv_temp = new List <string>(); List <Transform> parent_level = text_temp.transform.getParentLevel(); parent_level.Reverse(); string ID = ""; string describe = ""; for (int j = 0; j < parent_level.Count; j++) { ID += parent_level[j].name + "_"; describe += parent_level[j].name + "/"; } ID = ID.Remove(ID.Length - 1); describe = describe.Remove(describe.Length - 1); text_csv_temp.Add(ID); text_csv_temp.Add(describe); text_csv_temp.Add(""); text_csv_temp.Add(text_temp.text); csv_contents.Add(text_csv_temp); } string csv_str = CSVHelper.toCSV <string>(csv_contents); Debug.Log(csv_str); FileHelper.Save(csv_str, langCSV_path, false, true, Encoding.UTF8); }
private void Awake() { // if (instance != null && instance != this) // { // Destroy(this.gameObject); // } // // instance = this; // DontDestroyOnLoad( this.gameObject ); if (instance == null) { instance = this; DontDestroyOnLoad(gameObject); } else { Destroy(this); } //Get Update [must download content i.e. critical asset / csv] //Load all CSV data into dictionary lvMasterData = CSVHelper.Read(LV_CSV); //Bluprint //read from blueprint.csv //then seperate craft_type into different dictionary; }
public void initPlayer(int uid, int lv) { CSVHelper csv = CSVManager.getInstance().getCsvByName("unit"); if (csv == null) { return; } var data = csv.getColData(uid); atk = Convert.ToSingle(data[10]); speed = Convert.ToSingle(data[11]); hp = Convert.ToSingle(data[12]); crit = Convert.ToSingle(data[13]); magic = Convert.ToSingle(data[14]); atkdef = Convert.ToSingle(data[15]); magicdef = Convert.ToSingle(data[16]); luck = Convert.ToSingle(data[17]); hpValue = Convert.ToSingle(data[18]); atkValue = Convert.ToSingle(data[10]); atkdefValue = Convert.ToSingle(data[10]); magicdefValue = Convert.ToSingle(data[10]); dodgeValue = Convert.ToSingle(data[10]); hpValue = hpValue + (int)(lv * hp * 0.1f); this.level = lv; }
public static async Task Main(string[] args) { List <string> scopes = new List <string>() { "user.read", "Reports.Read.All" }; string token = await Authentication.getTokenAuthAsync(scopes); Console.WriteLine(token); args[0] = "D7"; if (args.Length != 0) { string graphAPIEndpoint = $"https://graph.microsoft.com/v1.0/reports/getEmailActivityUserDetail(period='{args[0]}')"; Console.Write(graphAPIEndpoint); HttpHelper httpHelper = new HttpHelper(); string filepath = Path.GetTempPath() + $"\\MailUsageReport{args[0]}.csv"; await httpHelper.GetHttpContentAsync(graphAPIEndpoint, token, filepath); await CSVHelper.sortCSV(filepath); SendEmailHelper emailHelper = new SendEmailHelper(System.Configuration.ConfigurationManager.AppSettings["Server"], System.Configuration.ConfigurationManager.AppSettings["Server"], 587); List <string> receivers = System.Configuration.ConfigurationManager.AppSettings["Receivers"].Split(',').ToList(); List <string> ccs = System.Configuration.ConfigurationManager.AppSettings["CCs"].Split(',').ToList(); await emailHelper.SendEmail(System.Configuration.ConfigurationManager.AppSettings["Email"], System.Configuration.ConfigurationManager.AppSettings["Password"], receivers, ccs, args[0] == "D7"?"Weekly Report Mail Usage" : "Monthly Report Mail Usage", args[0] == "D7"? "Weekly Report Mail Usage" : "Monthly Report Mail Usage", filepath); } }
//Funcao de processamento dos dados private string[] ParseData(string contentData) { //Divide o CSV por linhas string[] linhas = CSVHelper.GetLines(contentData); //Calcula quantidade de linhas e colunas myTarget.quantidadeDeLinhas = linhas.Length; myTarget.quantidadeDeColunas = CSVHelper.GetColumnsFromLine(linhas[0]).Length; ////Loop para achar a quantidade correta de colunas, achando a linha com a maior quantidade de colunas foreach (string linha in linhas) { int colunasNaLinha = CSVHelper.GetColumnsFromLine(linha).Length; if (colunasNaLinha > myTarget.quantidadeDeColunas) { myTarget.quantidadeDeColunas = colunasNaLinha; } } //Divide as linhas nas celulas List <string> data = new List <string>(); for (int linha = 0; linha < myTarget.quantidadeDeLinhas; linha++) { string[] celulasDaLinha = CSVHelper.GetColumnsFromLine(linhas[linha]); data.AddRange(celulasDaLinha); } return(data.ToArray()); }
/// <inheritdoc /> protected override void PostIterationStatistic(int iteration) { base.PostIterationStatistic(iteration); var lastIteration = iterations.Last.Value; agentList.Agents.ForEach(agent => { AgentState <Site> agentState; lastIteration.TryGetValue(agent, out agentState); var details = new AgentDetailsOutput { Iteration = iteration, AgentId = agent.Id, Age = agent[AlgorithmVariables.Age], IsAlive = agent[AlgorithmVariables.IsActive], Income = agent[AlgorithmVariables.AgentIncome], Expenses = agent[AlgorithmVariables.AgentExpenses], Savings = agent[AlgorithmVariables.HouseholdSavings], NumberOfDO = agent.AssignedDecisionOptions.Count, ChosenDecisionOption = agentState != null ? string.Join("|", agentState.DecisionOptionsHistories[DefaultDataSet].Activated.Select(opt => opt.Id)) : string.Empty }; CSVHelper.AppendTo(_outputFolder + string.Format(AgentDetailsOutput.FileName, agent.Id), details); }); }
public void formatStringTest() { //string message = "\"t,e,s,t,1\""; string message = "Say, \"Thank You.\" Teaching Kids the Power of Gratitude"; CSVHelper csv = new CSVHelper(); string result = csv.formatString(message); }
private void SendOfferTable(int index, string departmentname) { lock (DepartmentList) { foreach (var department in DepartmentList) { if (department.Name == departmentname) { var sendTable = department.OrderList.Clone(); if (index == -1) { foreach (DataRow row in department.OrderList.Rows) { if (row["Status"].ToString() == Global.UnKnown) { row["Status"] = Global.Wait; sendTable.Rows.Add(row.ItemArray); } } } else if (index >= 0) { sendTable.Rows.Add(department.OrderList.Rows[index].ItemArray); } var content = Mode.SendOrder.ToString(); content += " " + _client.ClientIP.ToString(); content += " " + department.IP; content += " " + CSVHelper.MakeCSV(sendTable); _client.SendContent(content); } } } }
private void DownloadExcel() { var dataTable = new DataTable(); dataTable.Columns.Add("序号"); dataTable.Columns.Add("订单编号"); dataTable.Columns.Add("订单状态"); dataTable.Columns.Add("订单关闭日期"); dataTable.Columns.Add("预约人"); dataTable.Columns.Add("总计"); var data = SearchData(); if (data != null && data.Count > 0) { DataRow newRow = null; for (int index = 0; index < data.Count; index++) { newRow = dataTable.NewRow(); newRow[0] = index + 1; newRow[1] = data[index].OrderNumber; newRow[2] = data[index].PayStatus; newRow[3] = data[index].ModifyTime; newRow[4] = data[index].CustomerName; newRow[5] = data[index].PayAmount; dataTable.Rows.Add(newRow); } } CSVHelper.DownloadAsSCV(Response, "餐饮服务验证码", dataTable); }
private void LoadCurrentFile() { var path = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); path += "\\LANTalk\\SaveFile\\SSP\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".csv"; if (File.Exists(path)) { MainTable = CSVHelper.ReadCSVToTable(path); } else { MainTable = new DataTable(); MainTable.Columns.Add("Line", typeof(string)); MainTable.Columns.Add("Model", typeof(string)); MainTable.Columns.Add("IPN", typeof(string)); MainTable.Columns.Add("MO", typeof(string)); MainTable.Columns.Add("P/N", typeof(string)); MainTable.Columns.Add("Order_Qty", typeof(string)); MainTable.Columns.Add("Start_Time", typeof(string)); MainTable.Columns.Add("Daily_Plan", typeof(string)); MainTable.Columns.Add("Actual_Output", typeof(string)); MainTable.Columns.Add("Man_Status", typeof(string)); MainTable.Columns.Add("Machine_Status", typeof(string)); MainTable.Columns.Add("Material_Status", typeof(string)); MainTable.Columns.Add("Method_Status", typeof(string)); } }
public static int GetDataCount(string filePath) { DataTable dt = new DataTable(); dt = CSVHelper.csv2dt(filePath, 0, dt); return(dt.Rows.Count); }
private void btnSub_Click(object sender, EventArgs e) { try { List <string> toAdd = new List <string>(); toAdd.Add(txtInput.Text); foreach (string item in Classifier.InputToList(txtInput.Text)) { toAdd.Add(item); } if (txtClass.Text == "") { toAdd.Add(cb_Class.Text); } else { toAdd.Add(txtClass.Text); } CSVHelper.AppendToCSV(toAdd); MessageBox.Show("Success! Input " + txtInput.Text + " added to dataset"); txtInput.Text = ""; txtClass.Text = ""; cb_Class.Text = ""; } catch (Exception ex) { MessageBox.Show("Error:" + ex.ToString()); } }
/// <summary> /// read accounts from csv file /// csv file's structure is following /// Email, Password, SecurityQuestion /// </summary> /// <param name="csvFilePath"></param> /// <returns></returns> public IList<Account> GetAccounts(string csvFilePath) { IList<Account> accounts = new List<Account>(); CSVHelper csvHelper = new CSVHelper(csvFilePath); foreach (string[] line in csvHelper) { Account account = new Account() { Email = line[0], Password = line[1], SecurityQuestion = line[2] }; accounts.Add(account); } return accounts; }