C#怎么导出dataGridView中的值到Excel

2024-11-09 10:07:33
推荐回答(1个)
回答(1):

代码如下:(自己好生研究下)
#region 将DataGridView控件中数据导出到Excel

///

/// 将DataGridView控件中数据导出到Excel

///

/// DataGridView对象

/// 是否显示Excel界面

///

public bool ExportDataGridview(DataGridView gridView, bool isShowExcle)
{

if (gridView.Rows.Count == 0)

return false;

//建立Excel对象
Excel.Application excel = new Excel.Application();

excel.Application.Workbooks.Add(true);

excel.Visible = isShowExcle;

//生成字段名称

for (int i = 0; i < gridView.ColumnCount; i++)
{

excel.Cells[1, i + 1] = gridView.Columns.ValueType == typeof(string))
{

excel.Cells = "'" + gridView[j, i].Value.ToString();

}

else
{

excel.Cells = gridView[j, i].Value.ToString();

}

}

}

return true;

}

#endregion
命名空间:using Microsoft.Internal.Performance;
调用代码: private void excel_Click(object sender, EventArgs e)
{
if (!comm.ExportDataGridview(info, true))

MessageBox.Show("表格中没有数据,无法导出数据!", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}