Created
June 22, 2023 17:28
-
-
Save ratozumbi/135858d38253a64e3a9f59beba109a11 to your computer and use it in GitHub Desktop.
exemple on how to create a CSV file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public void ExportCSV() | |
{ | |
string[] tableNames = | |
{ | |
"especialidade", "participante", "perfil", | |
"pergunta", "resposta", /*"questao",*/"quiz", | |
"setor", "tecnologia", "treinamento", "empresa" | |
}; | |
using (IDbConnection dbcon = new SqliteConnection(DataManager.Instance.Connection)) | |
{ | |
dbcon.Open(); | |
string directory = Application.persistentDataPath + "/export_" + DateTime.Now.Ticks + "/"; | |
foreach (string table in tableNames) | |
{ | |
try | |
{ | |
//create directory | |
string fileFullPath = directory + table + ".csv"; | |
Directory.CreateDirectory(Path.GetDirectoryName(fileFullPath)); | |
IDbCommand cmnd_read = dbcon.CreateCommand(); | |
cmnd_read.CommandText = "select * from " + table; | |
IDataReader reader = cmnd_read.ExecuteReader(); | |
StringBuilder sbHeader = new StringBuilder(); | |
for (var i = 0; i < reader.FieldCount; i++) | |
{ | |
sbHeader.Append(reader.GetName(i) + ","); | |
} | |
sbHeader.Remove(sbHeader.Length - 1, 1); | |
using (FileStream fileStream = new FileStream(fileFullPath, FileMode.Append, FileAccess.Write)) | |
using (StreamWriter streamWriter = new StreamWriter(fileStream)) | |
{ | |
//write head | |
streamWriter.WriteLine(sbHeader.ToString()); | |
//write content | |
while (reader.Read()) | |
{ | |
StringBuilder sbContent = new StringBuilder(); | |
for (int i = 0; i < reader.FieldCount; i++) | |
{ | |
string appender = ""; | |
//check if is base64 and decode | |
// if (Regex.IsMatch(appender,"^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$")) | |
if(table == "participante" && reader.GetName(i).Equals("email")) | |
{ | |
appender = Encryptor.Base64Decode(reader[i].ToString()); | |
} | |
else | |
{ | |
appender = reader[i].ToString(); | |
} | |
appender = '\"' + appender + '\"'; | |
//grab relevant tag data and set the csv line for the current row. | |
sbContent.Append(appender + ","); | |
} | |
sbContent.Remove(sbContent.Length - 1, 1); | |
streamWriter.WriteLine(sbContent.ToString()); | |
} | |
} | |
} | |
catch (Exception ex) | |
{ | |
Debug.LogError(ex.Message + ex.StackTrace); | |
} | |
} | |
ExternalApp.OpenExplorer(directory); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment