N
N
Neks_Minor2016-01-22 18:27:53
excel
Neks_Minor, 2016-01-22 18:27:53

How to write to excel file only some columns from dataGridView?

I put the table in the dataGridView1 container according to the SQL query:

SELECT b.ID_B as 'ID', b.NAME_B as 'Название', b.AUTHOR_B as 'Автор', pb.NAME_PB as 'Издательство', b.YEAR_B as 'Год издания', g.NAME_G  as 'Жанр' FROM BOOK b JOIN PUBLISHERS pb ON pb.ID_PB = b.PUBLISH_B JOIN GENRE g ON g.ID_G = bOOK.GENRE_B ORDER BY ID_B

DataTable dt = FirebirdConnect.ExecuteQuery(sql_query, fbConn);
dataGridView1.DataSource = dt;
dataGridView1.Columns[0].Visible = false; // Т.к. мне не нужно, чтобы колонка ID выводилась в контейнере

it goes something like this:
bdf7c2551f8e4e238ebdbf683c824ad3.png
When I save the table from the container to an Excel file, the last line is not displayed.
To work with Excel, I use the ClosedXML library.
Actually, the problem is only that the last line is not displayed.
Here is the code I am using to save the data to an excel file:
public void Export_Data_To_Excel(string filePath)
        {
                DataTable dt = new DataTable();

                foreach (DataGridViewColumn column in dataGridView1.Columns)
                {
                    if (column.HeaderText!="ID")
                    dt.Columns.Add(column.HeaderText);
                }

                foreach (DataGridViewRow row in dataGridView1.Rows)
                {                    
                    dt.Rows.Add();
                    foreach (DataGridViewCell cell in row.Cells)
                    {
                        if ((dt.Rows.Count - 1) != 0)
                            if (cell.ColumnIndex != 0)
                                dt.Rows[dt.Rows.Count - 2][cell.ColumnIndex-1] = cell.Value.ToString();
                    }
                }

                using (XLWorkbook wb = new XLWorkbook())
                {
                    wb.Worksheets.Add(dt, "Test");
                    wb.SaveAs(filePath);
                }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Churakov, 2016-01-26
@oufucom

dt.Rows.Add();
                    foreach (DataGridViewCell cell in row.Cells)
                    {
                        if ((dt.Rows.Count - 1) != 0)
                            if (cell.ColumnIndex != 0)
                                dt.Rows[dt.Rows.Count - 2][cell.ColumnIndex-1] = cell.Value.ToString();
                    }

Because you are writing to the previous line, not the one you just added.
And because of the condition, the if ((dt.Rows.Count - 1) != 0)
first pass in the loop is skipped. the line where "The Old Man and the Sea" is simply ignored.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question