using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
try
{
SaveFileDialog fileDialog = new SaveFileDialog();
fileDialog.Filter = “Excel(97-2003)|*.xls”;
if (fileDialog.ShowDialog() == System.Windows.Forms.DialogResult.Cancel)
{
return;
}
//不允许dataGridView显示添加行,负责导出时会报最后一行未实例化错误
dataGridView1.AllowUserToAddRows = false;
HSSFWorkbook workbook = new HSSFWorkbook();
ISheet sheet = workbook.CreateSheet(“Sheet1”);
IRow rowHead = sheet.CreateRow(0);
//填写表头
for (int i = 0; i < dataGridView1.Columns.Count; i++)
{
rowHead.CreateCell(i, CellType.String).SetCellValue(dataGridView1.Columns[i].HeaderText.ToString());
}
//填写内容
int arow = 0;
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
if (dataGridView1.Rows[i].Selected)
{
arow++;
IRow row = sheet.CreateRow(arow);
for (int j = 0; j < dataGridView1.Columns.Count; j++)
{
row.CreateCell(j, CellType.String).SetCellValue(dataGridView1.Rows[i].Cells[j].Value.ToString());
}
}
}
using (FileStream stream = File.OpenWrite(fileDialog.FileName))
{
workbook.Write(stream);
stream.Close();
}
MessageBox.Show("导出数据成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
GC.Collect();
}
catch (Exception)
{
GC.Collect();
}