I need to replace( , to ^) and( . to |)charaters while exporting data from sql to csv .Where can i change the code for mentioned character in below code
Code:
C#
command.CommandText = "SpGetData";
command.CommandType = CommandType.StoredProcedure;
SqlDataAdapter dataAdapter = new SqlDataAdapter(command.CommandText, connect);
dataAdapter.Fill(dataSet, "SpGetData");
DataTable t1 = dataSet.Tables["SpGetData"];
string csv1 = string.Empty;
foreach (DataColumn column in t1.Columns)
{
csv1 += column.ColumnName + ',';
}
foreach (DataRow row in t1.Rows)
{
foreach (DataColumn column in t1.Columns)
{
csv1 += row[column.ColumnName].ToString().Replace(",", ";") + ',';
}
}
string filename = exportPath + "Data" ;
File.WriteAllText(filename, csv1);
Naimish MakwanaRank #324 · 7.7K reputationPosted Mar 20, 2023, 11:29 AM EDT
Try below:
foreach (DataRow row in t1.Rows) { foreach (DataColumn column in t1.Columns) { string cellValue = row[column.ColumnName].ToString(); cellValue = cellValue.Replace(",", ";"); // Replace commas with semicolons cellValue = cellValue.Replace(".", "|"); // Replace dots with pipes csv1 += cellValue + ","; } }Thanks
Sachin SinghRank #66 · 26.2K reputationPosted Mar 20, 2023, 9:49 AM EDT
i guess this
csv1 += row[column.ColumnName].ToString().Replace(",", "^").Replace(".","|");Raj BhattRank #513 · 4.8K reputationPosted Mar 21, 2023, 2:51 AM EDT
using System.Data.SqlClient; // Connection string for SQL Server string connectionString = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;"; // SQL query to select data from the table string query = "SELECT column_name FROM table_name;"; // Create a SqlConnection object and open the connection using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); // Create a SqlCommand object with the SQL query and the SqlConnection using (SqlCommand command = new SqlCommand(query, connection)) { // Create a SqlDataReader object to read the data using (SqlDataReader reader = command.ExecuteReader()) { // Loop through the data and replace the characters while (reader.Read()) { string data = reader["column_name"].ToString(); string replacedData = data.Replace(",", "^").Replace(".", "|"); // Export the replaced data to a file or do something else with it // ... } } } // Close the connection connection.Close(); }Meghana MRank #8,429 · 222 reputationPosted Mar 21, 2023, 1:08 PM EDT
Excepted output format: this opened in notepad
column name:column1^column2^column3
row value:read^abc^bcd^efg|hij
in the above output( ', 'should replace with '^ ')and (bullet point symbol should replace with '| ')
Anandu G NathRank #681 · 3.5K reputationPosted Dec 27, 2023, 3:55 AM EST
csv+= row[column.ColumnName].ToString().Replace(",", "^").Replace(".","|");