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
Matti Tiira
NA
46
9.2k
Extra rows when exporting datagridview as csv
Mar 29 2019 5:53 AM
Hi!
I have a program that can export datagridview to csv.
All works well and all but one problem has occured.
The created csv file has two extra rows that are empty and they are causing me some trouble.
How can I get rid of them when exporting. Trimming them of in notepad is not really an option.
My code for the export looks like this:
private
void
btnExport_Click(
object
sender, EventArgs e)
{
// Don't save if no data is returned
if
(dataGridView1.Rows.Count == 0)
{
return
;
}
StringBuilder sb =
new
StringBuilder();
sb.AppendLine(
string
.Join(
","
, dataGridView1.Columns.Cast().Select(x => $
"\"{x.Name}\""
)));
foreach
(DataGridViewRow row
in
dataGridView1.Rows)
{
if
(!row.IsNewRow)
{
sb.AppendLine(
string
.Join(
","
, row.Cells.Cast().Select(c => $
"\"{c.Value ?? "
"}\""
)));
}
}
// Load up the save file dialog with the default option as saving as a .csv file.
SaveFileDialog sfd =
new
SaveFileDialog();
sfd.Filter =
"CSV files (*.csv)|*.csv"
;
if
(sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
// If they've selected a save location...
using
(System.IO.StreamWriter sw =
new
System.IO.StreamWriter(sfd.FileName,
false
))
{
// Write the stringbuilder text to the the file.
sw.WriteLine(sb.ToString());
}
}
All help is appreciated, Thanks.
-Matti
Reply
Answers (
4
)
Csv exporting with double quotes and commas
How to use Two ProgressBar in Same time using BackGroundWork