I'm trying to export my datagridview data to excel file using streamWriter it works fine but when export second time it replace the old file.
Here my code
private void button1_Click(object sender, EventArgs e)
{
if (dataGridView1.Rows.Count > 0)
{
try
{
// Bind Grid Data to Datatable
DataTable dt = new DataTable();
foreach (DataGridViewColumn col in dataGridView1.Columns)
{
dt.Columns.Add(col.HeaderText, col.ValueType);
}
int count = 0;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (count < dataGridView1.Rows.Count - 1)
{
dt.Rows.Add();
foreach (DataGridViewCell cell in row.Cells)
{
dt.Rows[dt.Rows.Count - 1][cell.ColumnIndex] = cell.Value.ToString();
}
}
count++;
}
DateTime now = DateTime.Now;
int hour = now.Hour;
int minute = now.Minute;
int second = now.Second;
int month = now.Month;
int day = now.Day;
int year = now.Year;
// Bind table data to Stream Writer to export data to respective folder
StreamWriter wr = new StreamWriter(@"C:\Users\admin\Downloads\\Book1.xls");
// Write Columns to excel file
for (int i = 0; i < dt.Columns.Count; i++)
{
wr.Write(dt.Columns[i].ToString().ToUpper() + "\t");
}
wr.WriteLine();
//write rows to excel file
for (int i = 0; i < (dt.Rows.Count); i++)
{
for (int j = 0; j < dt.Columns.Count; j++)
{
if (dt.Rows[i][j] != null)
{
wr.Write(Convert.ToString(dt.Rows[i][j]) + "\t");
}
else
{
wr.Write("\t");
}
}
wr.WriteLine();
}
wr.Close();
MessageBox.Show("Data Exported Successfully");
}
catch (Exception ex)
{
throw ex;
}
}
else
{
MessageBox.Show("No data found");
}
}
I'm trying to add date time in the file name
StreamWriter wr = new StreamWriter(@"C:\Users\admin\Downloads\\Extension Report Time", hour, " - ", minute, " - ", second".xls");
but it get error message
StreamWriter does not contain a constructor that takes 7 arugements
Try an interpolated string:
StreamWriter wr = new StreamWriter($"C:\\Users\\admin\\Downloads\\Extension Report Time {hour}-{minute}-{second}.xls");