more than one select pick datagridview and into excel

How can I pick more than one from datagridview and how to put these selected values into excel for c#  and and I need to create a new excel file when I assign these values
Gökmen Anıl YılmazStudentAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

MishaProgrammerCommented:
There is a good emaple of work with EXCEL and good excel dll.
https://www.gemboxsoftware.com/spreadsheet/examples/c-sharp-vb-net-write-excel/402
Also you can use microsoft interop excel.

There is a property DataGridView.SelectedRows in datagridview  (Windows Forms) . You can use in. In is collection. For example,
foreach (DataGridViewRow  row in YourGrid.SelectedRows )
{
// do someting with row
}

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Gökmen Anıl YılmazStudentAuthor Commented:
hi misha i dont understand pls Could you be a little more open
0
MishaProgrammerCommented:
Try to use this code. I tested it in my application. I select two rows in DataGrid with two columns.
		private void button5_Click(object sender, EventArgs e)
		{
			SpreadsheetInfo.SetLicense("FREE-LIMITED-KEY");
			ExcelFile ef = new ExcelFile(); // create class to work with excel
			ExcelWorksheet ws = ef.Worksheets.Add("Writing");

			for (int i = 0; i < dataGridView1.SelectedRows.Count; i++) // loop for selected rows
			{
				for (int j = 0; j < dataGridView1.SelectedRows[i].Cells.Count; j++) // loop for cells
				{
					ws.Cells[i, j].Value = dataGridView1.SelectedRows[i].Cells[j].Value; // write values to excel class
				}				
			}
			ef.Save("Hello World.xlsx"); // write data to excel file 

		}

Open in new window


Also you can use other style for excel cells and more other good thing, You can find it in examples in my link. Don't forget to install GemBox with NuGet.
0
Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

Gökmen Anıl YılmazStudentAuthor Commented:
thanks for answers. I will try and return to you tomorrow.
0
it_saigeDeveloperCommented:
If you don't need to apply any formatting to your output, then a delimited file is all you need to output (comma delimited being the most common).  Proof of concept:

Form1.cs -
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Windows.Forms;

namespace EE_Q29093586
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void OnClick(object sender, EventArgs e)
        {
            DialogResult result = fileDialog.ShowDialog();
            if (result == DialogResult.OK)
            {
                dataGridView1.ExportToFile(fileDialog.FileName, (Delimiter)comboBox1.SelectedValue, checkBox1.Checked);
            }
        }

        private void OnLoad(object sender, EventArgs e)
        {
            comboBox1.DataSource = (from d in Enum.GetValues(typeof(Delimiter)).Cast<Delimiter>() select new { DisplayMember = d.ToString(), ValueMember = d }).ToList();
            comboBox1.DisplayMember = "DisplayMember";
            comboBox1.ValueMember = "ValueMember";
            dataGridView1.DataSource = (from i in Enumerable.Range(0, 50) select new { ID = i, FirstName = $"FirstName{i}", LastName = $"LastName{i}", Birthdate = DateTime.Now.AddDays(-(9 * i)), IsWorking = i % 2 == 0 }).ConvertToDataTable();
        }
    }

    enum Delimiter
    {
        [Description(",")]
        Comma = 0,
        [Description("|")]
        Pipe = 1,
        [Description("\t")]
        Tab = 2
    }

    static class Extensions
    {
        public static DataTable ConvertToDataTable<T>(this IEnumerable<T> source, string name = "")
        {
            DataTable table = new DataTable("");
            var properties = TypeDescriptor.GetProperties(typeof(T));
            foreach (PropertyDescriptor property in properties)
            {
                if (property.PropertyType.IsGenericType && property.PropertyType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
                    table.Columns.Add(property.Name, property.PropertyType.GetGenericArguments()[0]);
                else
                    table.Columns.Add(property.Name, property.PropertyType);
            }

            object[] values = new object[properties.Count];
            foreach (var item in source)
            {
                for (int i = 0; i < properties.Count; i++)
                    values[i] = properties[i].GetValue(item);
                table.Rows.Add(values);
            }
            return table;
        }

        public static void ExportToFile(this DataGridView source, string fileName, Delimiter delimiter = Delimiter.Comma, bool includeHeaders = false)
        {
            source.ExportToFile(new FileInfo(fileName), delimiter, includeHeaders);
        }

        public static void ExportToFile(this DataGridView source, FileInfo file, Delimiter delimiter = Delimiter.Comma, bool includeHeaders = false)
        {
            var stream = default(FileStream);
            var writer = default(StreamWriter);
            try
            {
                if (source?.Rows?.Count == 0 ||source?.SelectedRows?.Count == 0)
                {
                    MessageBox.Show("Nothing to export");
                    return;
                }

                if (file.Exists)
                    file.Delete();

                using (stream = new FileStream(file.FullName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
                using (writer = new StreamWriter(stream))
                {
                    writer.BaseStream.Seek(0, SeekOrigin.Begin);

                    if (includeHeaders)
                        writer.WriteLine(string.Join(delimiter.GetDescription(), (from column in source.Columns.Cast<DataGridViewColumn>() select column.HeaderText).ToArray()));

                    foreach (DataGridViewRow row in source.SelectedRows.Cast<DataGridViewRow>().Reverse())
                        writer.WriteLine(string.Join(delimiter.GetDescription(), (from cell in row.Cells.Cast<DataGridViewCell>() select cell.Value).ToArray()));
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Source: {ex.Source}{Environment.NewLine}Exception: {ex}{Environment.NewLine}Message: {ex.Message}", "Exception Reported", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        public static string GetDescription(this Enum value)
        {
            FieldInfo field = value.GetType().GetField(value.ToString());
            DescriptionAttribute[] attributes = (DescriptionAttribute[])field.GetCustomAttributes(typeof(DescriptionAttribute), false);
            return attributes.Length > 0 ? attributes[0].Description : value.ToString();
        }
    }
}

Open in new window

Form1.Designer.cs -
namespace EE_Q29093586
{
    partial class Form1
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.btnExport = new System.Windows.Forms.Button();
            this.fileDialog = new System.Windows.Forms.OpenFileDialog();
            this.dataGridView1 = new System.Windows.Forms.DataGridView();
            this.comboBox1 = new System.Windows.Forms.ComboBox();
            this.checkBox1 = new System.Windows.Forms.CheckBox();
            ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();
            this.SuspendLayout();
            // 
            // btnExport
            // 
            this.btnExport.Location = new System.Drawing.Point(534, 275);
            this.btnExport.Name = "btnExport";
            this.btnExport.Size = new System.Drawing.Size(75, 23);
            this.btnExport.TabIndex = 0;
            this.btnExport.Text = "Export";
            this.btnExport.UseVisualStyleBackColor = true;
            this.btnExport.Click += new System.EventHandler(this.OnClick);
            // 
            // fileDialog
            // 
            this.fileDialog.CheckFileExists = false;
            this.fileDialog.CheckPathExists = false;
            this.fileDialog.DefaultExt = "csv";
            this.fileDialog.FileName = "ExportedRows";
            this.fileDialog.Filter = "\"Excel Files|*.csv;*.xls;*.xlsx\"";
            this.fileDialog.Title = "Choose output file...";
            // 
            // dataGridView1
            // 
            this.dataGridView1.AllowUserToAddRows = false;
            this.dataGridView1.AllowUserToDeleteRows = false;
            this.dataGridView1.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill;
            this.dataGridView1.AutoSizeRowsMode = System.Windows.Forms.DataGridViewAutoSizeRowsMode.AllCells;
            this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            this.dataGridView1.Dock = System.Windows.Forms.DockStyle.Top;
            this.dataGridView1.Location = new System.Drawing.Point(0, 0);
            this.dataGridView1.Name = "dataGridView1";
            this.dataGridView1.ReadOnly = true;
            this.dataGridView1.RowHeadersVisible = false;
            this.dataGridView1.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect;
            this.dataGridView1.Size = new System.Drawing.Size(621, 243);
            this.dataGridView1.TabIndex = 1;
            // 
            // comboBox1
            // 
            this.comboBox1.FormattingEnabled = true;
            this.comboBox1.Location = new System.Drawing.Point(372, 249);
            this.comboBox1.Name = "comboBox1";
            this.comboBox1.Size = new System.Drawing.Size(121, 21);
            this.comboBox1.TabIndex = 2;
            // 
            // checkBox1
            // 
            this.checkBox1.AutoSize = true;
            this.checkBox1.Location = new System.Drawing.Point(499, 252);
            this.checkBox1.Name = "checkBox1";
            this.checkBox1.Size = new System.Drawing.Size(110, 17);
            this.checkBox1.TabIndex = 3;
            this.checkBox1.Text = "Include Headers?";
            this.checkBox1.UseVisualStyleBackColor = true;
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(621, 310);
            this.Controls.Add(this.checkBox1);
            this.Controls.Add(this.comboBox1);
            this.Controls.Add(this.dataGridView1);
            this.Controls.Add(this.btnExport);
            this.Name = "Form1";
            this.Text = "Form1";
            this.Load += new System.EventHandler(this.OnLoad);
            ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.Button btnExport;
        private System.Windows.Forms.OpenFileDialog fileDialog;
        private System.Windows.Forms.DataGridView dataGridView1;
        private System.Windows.Forms.ComboBox comboBox1;
        private System.Windows.Forms.CheckBox checkBox1;
    }
}

Open in new window

Which produces the following ouput:

Initial Load -Capture.PNGMaking the selections -Capture.PNG
Hitting Export -Capture.PNGNotepad Output -Capture.PNG
Excel Output -Capture.PNG
-saige-
0
Gökmen Anıl YılmazStudentAuthor Commented:
thanks for good answer. How can I export an image column with a specific DataGridView?  so how to export to excel
0
it_saigeDeveloperCommented:
As I had stated:
If you don't need to apply any formatting to your output, then a delimited file is all you need to output (comma delimited being the most common).
Since you want to output images (which would require formatting) then you will have to use something along the lines of which Misha posted about or the native interop assemblies for Excel.

Here is a previous EE_PAQ which discusses an interop method:

https://www.experts-exchange.com/questions/24594067/C-exporting-DataGridView-with-images-to-excel.html

-saige-
0
Gökmen Anıl YılmazStudentAuthor Commented:
the data from the database will fill the DataGridView i do so that i do it. Later, when I press the button, the lines I selected will be exported to excel
0
MishaProgrammerCommented:
There is no activity from author.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.