Excel file save to local drive in C# Windows form
I have a grid view with data. I want to download or save it to my local drive in excel format. excel file with row data or without row only header text name when click on button.
Excel file save to local drive in C# Windows form
I have a grid view with data. I want to download or save it to my local drive in excel format. excel file with row data or without row only header text name when click on button.
//create a data table//
DataTable dt = new DataTable();
//Adding the Columns only for header text
dt.Columns.Add("ITEM");
dt.Columns.Add("ODERQTY");
dt.Columns.Add("EXPDAT");
dt.Columns.Add("STK");
//Adding the Rows if you want. Otherwise ignore this foreach loop//
foreach (DataGridViewRow row in dataGridView1.Rows)
{
dt.Rows.Add();
foreach (DataGridViewCell cell in row.Cells)
{
dt.Rows[dt.Rows.Count - 1][cell.ColumnIndex] = cell.Value.ToString();
}
}
//save or export part/
SaveFileDialog saveDialog = new SaveFileDialog();
DialogResult result = saveDialog.ShowDialog();
if (result == DialogResult.OK)
{
String fileName = saveDialog.FileName;
//your code to save the file;
using (XLWorkbook wb = new XLWorkbook())
{
wb.Worksheets.Add(dt, "Sheet1");
wb.SaveAs(fileName+".xlsx");
MessageBox.Show("Excel Downloaded.");
}
}