-1

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.

1

1 Answer 1

0
//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.");
                    }
                }    


           
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.