Answer the question
In order to leave comments, you need to log in
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 выводилась в контейнере
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
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();
}
if ((dt.Rows.Count - 1) != 0)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question