Save files from a Datagridview

Asked

Viewed 657 times

7

I would like to know how to get all the content that was passed to a Datagridview and save it in an Excel file. So far I have it:

private void btnDiretorio_Click(object sender, EventArgs e)
        {

            folderBrowserDialog.RootFolder = Environment.SpecialFolder.DesktopDirectory;
            folderBrowserDialog.SelectedPath = openFileDialog.InitialDirectory;
            folderBrowserDialog.ShowNewFolderButton = true;
            DialogResult result = folderBrowserDialog.ShowDialog();

            if (result == DialogResult.OK)
            {
                List<string> selectedPath = listaArquivos(folderBrowserDialog.SelectedPath);

                foreach (string s in selectedPath)
                {
                    grvShowFile.Rows.Add(Path.GetFileName(s), s);
                }
            }
        }

This code is from a button that selects all files in a directory and its subfolders. Note that Datagridview is being filled normally.

 private void btnPesquisar_Click(object sender, EventArgs e)
        {
            if (this.cboParametro.Text == "" || this.cboParametro.Text == "Ola"){
                MessageBox.Show("Parametro inválido, por favor tente novamente.");
            }

            string[] arrayParam = { "FROM", "SELECT", "WHERE", "UPDATE", "" };
            //Dictionary<string, string> getParam = new Dictionary<string, string>();
            //getParam.Add("FROM", "WHERE");
            //getParam.Add("SELECT", "Private");
            StreamReader DirectorySR = new StreamReader(folderBrowserDialog.SelectedPath);
            while (!DirectorySR.EndOfStream)
            {
                string read = DirectorySR.ReadToEnd();
                DirectorySR.Close();

            }
        }

This is where I am losing myself, this button needs to receive a parameter that will be passed by the user ( OK! ) and then load the files that were passed in Datagridview ( That’s where I’m not being able to continue ) and read file by file passing that array that was created with the specific words.

I’m a beginner in C# and I can’t continue this part.

  • your question is a little confused, can not understand exactly what you need, you speak of saving the content of DataGridView in an Excel file and then in the code, implies that you want to do a search in the files that are in the DataGridView using the arrayParam, take a look at [Ask] and adjust your question

  • Rodolfo, also not understood if you want to export the contents of the grid to excel or want to open a file.

1 answer

1

You can work with the objects of interoperability of the Office

Here is an example of a function that exports data from a DataGridView

private void ExportToExcel()
{
    // Creating a Excel object.
    Microsoft.Office.Interop.Excel._Application excel = new Microsoft.Office.Interop.Excel.Application();
    Microsoft.Office.Interop.Excel._Workbook workbook = excel.Workbooks.Add(Type.Missing);
    Microsoft.Office.Interop.Excel._Worksheet worksheet = null;

    try
    {

        worksheet = workbook.ActiveSheet;

        worksheet.Name = "ExportedFromDatGrid";

        int cellRowIndex = 1;
        int cellColumnIndex = 1;

        //Loop through each row and read value from each column.
        for (int i = 0; i < dgvCityDetails.Rows.Count - 1; i++)
        {
            for (int j = 0; j < dgvCityDetails.Columns.Count; j++)
            {
                // Excel index starts from 1,1. As first Row would have the Column headers, adding a condition check.
                if (cellRowIndex == 1)
                {
                    worksheet.Cells[cellRowIndex, cellColumnIndex] = dgvCityDetails.Columns[j].HeaderText;
                }
                else
                {
                    worksheet.Cells[cellRowIndex, cellColumnIndex] = dgvCityDetails.Rows[i].Cells[j].Value.ToString();
                }
                cellColumnIndex++;
            }
            cellColumnIndex = 1;
            cellRowIndex++;
        }

        //Getting the location and file name of the excel to save from user.
        SaveFileDialog saveDialog = new SaveFileDialog();
        saveDialog.Filter = "Excel files (*.xlsx)|*.xlsx|All files (*.*)|*.*";
        saveDialog.FilterIndex = 2;

        if (saveDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            workbook.SaveAs(saveDialog.FileName);
            MessageBox.Show("Export Successful");
        }               
    }
    catch (System.Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
    finally
    {
        excel.Quit();
        workbook = null;
        excel = null;
    }

}

The complete example you can find in the following link https://code.msdn.microsoft.com/How-to-Export-DataGridView-62f1f8ff

Browser other questions tagged

You are not signed in. Login or sign up in order to post.