Search code examples
c#datagridviewopenfiledialogsavefiledialog

C# save DataGridView after editing (overwrite Excel file that was imported)


I have a small form which has 3 Buttons (Browse & updateExcel & saveExcel), a ComboBox (comboBox1) and a DataGridView (dataGridView1)

The first button lets you select an Excel file and then loads in the file to the DataGridView:

private void Browse_Click(object sender, EventArgs e)
    {

        OpenFileDialog op = new OpenFileDialog();
        op.InitialDirectory = @"C:\";
        op.Title = "Browse Excel Files";
        op.CheckFileExists = true;
        op.CheckPathExists = true;
        op.DefaultExt = "xls";
        op.Filter = "Excel Files|*.xls;*.xlsx;*.xlsm;*.csv";
        op.FilterIndex = 2;
        op.RestoreDirectory = true;
        op.ReadOnlyChecked = true;
        op.ShowReadOnly = true;

        if (op.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            if (File.Exists(op.FileName))
            {
                string[] Arr = null;
                Arr = op.FileName.Split('.');
                if (Arr.Length > 0)
                {
                    if (Arr[Arr.Length - 1] == "xls")
                        sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
                        op.FileName + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'";
                }
                else if (Arr[Arr.Length - 1] == "xlsx")
                {
                    sConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + op.FileName + ";Extended Properties='Excel 12.0 Xml;HDR=YES';";
                }
            }
            FillData();
        }
    }

This also uses the following code:

    public string sConnectionString;
    private void FillData()
    {
        if (sConnectionString.Length > 0)
        {
            OleDbConnection cn = new OleDbConnection(sConnectionString);
            {
                cn.Open();
                DataTable dt = new DataTable();
                OleDbDataAdapter Adpt = new OleDbDataAdapter("select * from [sheet1$]", cn);
                Adpt.Fill(dt);
                dataGridView1.DataSource = dt;
            }
            try { }
            catch (Exception ex)
            {
            }
        }
    }

Then after you select a value from the ComboBox you can then update the DataGridView with this value as required by clicking the updateExcel button which uses this code:

    private void updateExcel_Click(object sender, EventArgs e)
    {
        for (int i = 0; i < dataGridView1.RowCount - 1; i++)
        {
            dataGridView1[2, i].Value = ConsigneeCombo.Text;
        }
    }

What I want to do is then click the Save button (saveExcel) and it save the loaded file with an Are you sure you want to save? Yes or No standard Windows dialogue box.

I have tried using the SaveFileDialogue (saveFileDialog1) to do this:

    private void saveExcel_Click(object sender, EventArgs e)
    {
        SaveFileDialog saveFileDialog1 = new SaveFileDialog();
        saveFileDialog1.InitialDirectory = @"C:\";
        saveFileDialog1.Title = "Save Excel File";
        saveFileDialog1.DefaultExt = "xls";
        saveFileDialog1.Filter = "Excel Files|*.xls;*.xlsx;*.xlsm;*.csv";
        saveFileDialog1.FilterIndex = 2;
        saveFileDialog1.ShowDialog();

        if (saveFileDialog1.FileName != "")
        {
            System.IO.FileStream fs = (System.IO.FileStream)saveFileDialog1.OpenFile();
            fs.Close();
        }
    }

But this doesn't work as tries to save the file as a new file (with a new tab name etc) and it actually doesn't recognise the file type.


Solution

  • I solved this by using the following code:

        private void saveExcel_Click(object sender, EventArgs e)
        {
    
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.InitialDirectory = @"C:\";
            sfd.Title = "Save Excel Files";
            sfd.CheckPathExists = true;
            sfd.DefaultExt = "xls";
            sfd.Filter = "Excel Files|*.xls;*.xlsx;*.xlsm;*.csv";
            sfd.FileName = "*.csv";
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                ToCsV(dataGridView1, sfd.FileName);
            }
        }