TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
Answers
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
Forums
Monthly Leaders
Forum guidelines
Jes Sie
741
1.2k
284.6k
Export Postgres Table to csv File using C#
Jul 11 2020 12:33 AM
I tried to export table values from Postgres to csv file using c#. Below is my code;
private
void
ExportFileFromLocalDb1()
{
// Export path and file.
string
exportPath =
"D:\\JESAP files\\LTS Project\\Test\\"
;
//D:\JESAP files\LTS Project\Test
string
exportCsv =
"transaction.csv"
;
// Stream writer for CSV file.
StreamWriter csvFile =
null
;
// Check to see if the file path exists.
if
(Directory.Exists(exportPath))
{
try
{
using
(NpgsqlConnection con = ClassConnection.GetDbCon())
{
NpgsqlCommand cmd =
new
NpgsqlCommand(
"SELECT id, date, bankbooknumber, transaction_code_id, amount, debit_acc_number, credit_acc_number, user_id, vbcode, synchronized, description FROM public.transactions;"
, con);
cmd.CommandType = CommandType.Text;
con.Open();
NpgsqlDataReader rdr = cmd.ExecuteReader();
// Stream writer for CSV file.
csvFile =
new
StreamWriter(@exportPath + exportCsv);
// Add the headers to the CSV file.
csvFile.WriteLine(
string
.Format(
"\"{0}\",\"{1}\",\"{2}\",\"{4}\",\"{5}\",\"{6}\",\"{7}\",\"{8}\",\"{9}\",\"{10}\""
,
rdr.GetName(0),
rdr.GetName(1),
rdr.GetName(2),
rdr.GetName(3),
rdr.GetName(4),
rdr.GetName(5),
rdr.GetName(6),
rdr.GetName(7),
rdr.GetName(8),
rdr.GetName(9),
rdr.GetName(10)
));
// Construct CSV file data rows.
while
(rdr.Read())
{
// Add line from reader object to new CSV file.
csvFile.WriteLine(
string
.Format(
"\"{0}\",\"{1}\",\"{2}\",\"{4}\",\"{5}\",\"{6}\",\"{7}\",\"{8}\",\"{9}\",\"{10}\""
,
rdr.GetName(0),
rdr.GetName(1),
rdr.GetName(2),
rdr.GetName(3),
rdr.GetName(4),
rdr.GetName(5),
rdr.GetName(6),
rdr.GetName(7),
rdr.GetName(8),
rdr.GetName(9),
rdr.GetName(10)
));
}
// Message stating export successful.
MessageBox.Show(
"Data export successful."
);
}
}
catch
(Exception e)
{
throw
e;
}
finally
{
csvFile.Close();
}
}
else
{
// Display a message stating file path does not exist.
MessageBox.Show(
"File path does not exist."
);
}
}
the export is successful, but, I only get the header for all rows. See image below:
Please help.
Reply
Answers (
3
)
Display pdf file from postgresql to a datagridview using c#
Active directory