简体   繁体   English

编辑后C#保存DataGridView(覆盖导入的Excel文件)

[英]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 ) 我有一个小表格,其中有3个ButtonsBrowseupdateExcelsaveExcel ), ComboBoxcomboBox1 )和DataGridViewdataGridView1

The first button lets you select an Excel file and then loads in the file to the DataGridView : 第一个按钮使您可以选择一个Excel文件,然后将该文件加载到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: 然后,从ComboBox选择一个值之后,可以通过单击使用以下代码的updateExcel按钮,根据需要使用该值更新DataGridView

    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? 然后,我要执行的操作是单击“保存”按钮( saveExcel ),并使用来保存加载的文件。 Are you sure you want to save? Yes or No standard Windows dialogue box. YesNo标准Windows对话框。

I have tried using the SaveFileDialogue ( saveFileDialog1 ) to do this: 我尝试使用SaveFileDialoguesaveFileDialog1 )执行此操作:

    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. 但这不起作用,因为尝试将文件另存为新文件(具有新的标签名等),并且实际上无法识别文件类型。

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);
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM