仅将可见的 datagridview 列导出到 excel

仅将可见的 datagridview 列导出到 excel

需要帮助将仅可见的 DataGridView 列导出到 excel,我有此代码用于隐藏 DataGridView 中的列。this.dg1.Columns[0].Visible = false; 然后我有按钮单击事件用于导出到 excel。

// creating Excel Application
Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel._Application();

// creating new WorkBook within Excel application
Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);

// creating new Excelsheet in workbook
Microsoft.Office.Interop.Excel._Worksheet worksheet = null;

// see the excel sheet behind the program
app.Visible = true;

// get the reference of first sheet. By default its name is Sheet1.
// store its reference to worksheet
worksheet = workbook.Sheets["Sheet1"];
worksheet = workbook.ActiveSheet;


// changing the name of active sheet
worksheet.Name = "PIN korisnici";

// storing header part in Excel
for (int i = 1; i < dg1.Columns.Count + 1; i++)
{
worksheet.Cells[1, i] = dg1.Columns[i - 1].HeaderText;
}
// storing Each row and column value to excel sheet
for (int i = 0; i < dg1.Rows.Count - 1; i++)
{
for (int j = 0; j < dg1.Columns.Count; j++)
{
worksheet.Cells[i + 2, j + 1] = dg1.Rows[i].Cells[j].Value.ToString();
}
}

但我只想导出可见的列,同时我得到所有的列,任何人,都可以帮忙。

答案1

只需构建可见列的列表,然后仅导出这些列,例如

List<DataGridViewColumn> listVisible = new List<DataGridViewColumn>();
foreach( DataGridViewColumn col in dg1.Columns )
{
    if (col.Visible)
         listVisible.Add(col);
}

然后当你遍历列时使用你的“可见”列表,例如

for (int i = 0; i < listVisible.Count; i++)
{
    worksheet.Cells[1, i + 1] = listVisible[i].HeaderText;
}

for (int i = 0; i < dg1.Rows.Count - 1; i++)
{
    for (int j = 0; j < listVisible.Count; j++)
    {
        worksheet.Cells[i + 2, j + 1] = dg1.Rows[i].Cells[listVisible[j].Name].Value.ToString();
    }
}

相关内容