#region 导出dataViewGrid视图中的数据为xls格局
private void btnExportList_Click(object sender, EventArgs e)
{
string fname = string.Empty;
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = “表格文件|*.xls”;
sfd.DefaultExt = “xls”;
if (sfd.ShowDialog() == DialogResult.OK)
{
fname = sfd.FileName;
}
else
{
return;
}
//导出当前dataGridView中的所有数据到xls文件
//1.引入库文件,新建lib文件夹,,复制相关文件
//2.在项目中添加对这几个dll的引用
//3.在内存中成立 excel表文件
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.CreateSheet(“第一页”);
//创建标题头
HSSFRow title = sheet.CreateRow(0);
title.CreateCell(0).SetCellValue(“编号”);
title.CreateCell(1).SetCellValue(“姓名”);
title.CreateCell(2).SetCellValue(“性别”);
title.CreateCell(3).SetCellValue(“春秋”);
title.CreateCell(4).SetCellValue(“地点”);
title.CreateCell(5).SetCellValue(“电话”);
title.CreateCell(6).SetCellValue(“生日”);
for (int rowindex = 0; rowindex < dgvStudens.RowCount; rowindex++)
{
//创建第一行
HSSFRow row = sheet.CreateRow(rowindex + 1);
for (int colindex = 0; colindex < dgvStudens.Rows[rowindex].Cells.Count; colindex++)
{
row.CreateCell(colindex).SetCellValue((dgvStudens.Rows[rowindex].Cells[colindex].Value == null) ? null : dgvStudens.Rows[rowindex].Cells[colindex].Value.ToString());
}
////创建第一行的第一列
//HSSFCell cell = row.CreateCell(0);
//cell.SetCellType(3);
//cell.SetCellValue(dgvStudens.Rows[rowindex].Cells[0].Value.ToString());
////第一行第2列
//row.CreateCell(1).SetCellValue(dgvStudens.Rows[rowindex].Cells[1].Value.ToString());
////第一行第3列
//row.CreateCell(2).SetCellValue(dgvStudens.Rows[rowindex].Cells[2].Value.ToString());
////第一行第4列,age,可能会为空
//// row.CreateCell(3).SetCellValue(dgvStudens.Rows[0].Cells[3].Value.ToString());
//row.CreateCell(3).SetCellValue((dgvStudens.Rows[rowindex].Cells[3].Value == null) ? null : dgvStudens.Rows[rowindex].Cells[3].Value.ToString());
}
using (FileStream fs = new FileStream(fname, FileMode.Create))
{
workbook.Write(fs);
}