C# 怎么导出dataGridView中的值到Excel
在系统应用过程中,数据是系统的核心。如果直接在应用软件中看数据,有时也有些不便,所以就会把系统数据转换成Excel格式,便于处理。下面小编将在VS2010中将dataGridView导出为Excel中。
方法/步骤
-
添加Office Excel引用,在.net下面。
-
程序代码引用:using Excel = Microsoft.Office.Interop.Excel;
-
添加事件控件“导出Excel”
-
双击“导出Excel”空间添加代码:
private void button2_Click(object sender, EventArgs e)
{
string fileName = "";
string saveFileName = "";
SaveFileDialog saveDialog = new SaveFileDialog();
saveDialog.DefaultExt = "xls";
saveDialog.Filter = "Excel文件|*.xls";
saveDialog.FileName = fileName;
saveDialog.ShowDialog();
saveFileName = saveDialog.FileName;
if (saveFileName.IndexOf(":") < 0) return; //被点了取消
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
if (xlApp == null)
{
MessageBox.Show("无法创建Excel对象,您的电脑可能未安装Excel");
return;
}
Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks;
Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];//取得sheet1
//写入标题
for (int i = 0; i < dataGridView1.ColumnCount; i++)
{worksheet.Cells[1, i + 1] = dataGridView1.Columns[i].HeaderText;}
//写入数值
for (int r = 0; r < dataGridView1.Rows.Count; r++)
{ for (int i = 0; i < dataGridView1.ColumnCount; i++)
{
worksheet.Cells[r + 2, i + 1] = dataGridView1.Rows[r].Cells[i].Value;
}
System.Windows.Forms.Application.DoEvents();
}
worksheet.Columns.EntireColumn.AutoFit();//列宽自适应
MessageBox.Show(fileName + "资料保存成功", "提示", MessageBoxButtons.OK);
if (saveFileName != "")
{
try
{workbook.Saved = true;
workbook.SaveCopyAs(saveFileName); //fileSaved = true;
}
catch (Exception ex)
{//fileSaved = false;
MessageBox.Show("导出文件时出错,文件可能正被打开! " + ex.Message);
}
}
xlApp.Quit();
GC.Collect();//强行销毁 }
}
-
重新生成“解决方案”后测试。
-
通过以上,成功的将datagridview中的值导出到excel中了。