public void ExportDataToExcel(DataGridView dgv)
{
if (dgv.Rows.Count == 0)
{
return;
}
saveFileDialog1.Title = "请选择要导出的位置";
saveFileDialog1.Filter = "Excel文件| *.xls";
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
if (saveFileDialog1.FileName != "")
{
//创建Excel文件的对象
NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();
//添加一个sheet
NPOI.SS.UserModel.ISheet sheet1 = book.CreateSheet("Sheet1");
//给sheet1添加第一行的头部标题
sheet1.SetColumnWidth(0, 20 * 256);//设置高度和宽度
sheet1.SetColumnWidth(1, 20 * 256);//设置高度和宽度
sheet1.SetColumnWidth(2, 30 * 256);//设置高度和宽度
sheet1.SetColumnWidth(3, 40 * 256);//设置高度和宽度
sheet1.SetColumnWidth(4, 20 * 256);//设置高度和宽度
sheet1.SetColumnWidth(5, 20 * 256);//设置高度和宽度
NPOI.SS.UserModel.IRow row1 = sheet1.CreateRow(0);
row1.CreateCell(0).SetCellValue("标题");
row1.CreateCell(1).SetCellValue("标题");
row1.CreateCell(2).SetCellValue("标题");
row1.CreateCell(3).SetCellValue("标题");
row1.CreateCell(4).SetCellValue("标题");
row1.CreateCell(5).SetCellValue("标题");
把数据循环的导入到Excel中
for (int i = 0; i < dgv.Rows.Count; i++)
{
NPOI.SS.UserModel.IRow rowtemp = sheet1.CreateRow(i + 1);
rowtemp.CreateCell(0).SetCellValue(dgv.Rows[i].Cells["dataGridViewTextBoxColumn53"].Value.ToString());
rowtemp.CreateCell(1).SetCellValue(dgv.Rows[i].Cells["dataGridViewTextBoxColumn54"].Value.ToString());
rowtemp.CreateCell(2).SetCellValue(dgv.Rows[i].Cells["dataGridViewTextBoxColumn55"].Value.ToString());
rowtemp.CreateCell(3).SetCellValue(dgv.Rows[i].Cells["dataGridViewTextBoxColumn56"].Value.ToString());
rowtemp.CreateCell(4).SetCellValue(dgv.Rows[i].Cells["dataGridViewTextBoxColumn57"].Value.ToString());
rowtemp.CreateCell(5).SetCellValue(dgv.Rows[i].Cells[""]. Value. ToString());
}
FileStream ms = File.OpenWrite(saveFileDialog1.FileName.ToString());
try
{
book.Write(ms);
ms.Seek(0, SeekOrigin.Begin);
MessageBox.Show("导出成功");
}
catch
{
MessageBox.Show("导出失败!");
}
finally
{
if (ms != null)
{
ms.Close();
}
}
}
}
}