.NET使用NPOI从datagridview导出excel
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
public void ExportExcel(string fileName, DataGridView dgv)
{
string saveFileName = "";
SaveFileDialog saveDialog = new SaveFileDialog();
saveDialog.DefaultExt = "xls";
saveDialog.Filter = "Excel文件|*.xls";
saveDialog.FileName = fileName;
saveDialog.ShowDialog();
saveFileName = saveDialog.FileName;
HSSFWorkbook workbook = new HSSFWorkbook();
MemoryStream ms = new MemoryStream();
NPOI.SS.UserModel.ISheet sheet = workbook.CreateSheet("Sheet1");
int rowCount = dataGridView3.Rows.Count;
int colCount = dataGridView3.Columns.Count;
//设置表头
//IRow cells = sheet.CreateRow(0);
//cells.CreateCell(0).SetCellValue("编号");
//cells.CreateCell(1).SetCellValue("任务名称");
//cells.CreateCell(2).SetCellValue("核心内容");
for (int i = 0; i < rowCount; i++)
{
NPOI.SS.UserModel.IRow dataRow = sheet.CreateRow(i);
for (int j = 0; j < colCount; j++)
{
if (dataGridView3.Columns[j].Visible && dataGridView3.Rows[i].Cells[j].Value != null)
{
NPOI.SS.UserModel.ICell cell = dataRow.CreateCell(j);
cell.SetCellValue(dataGridView3.Rows[i].Cells[j].Value.ToString());
}
}
}
//自适应宽度
for (int columnNum = 0; columnNum <= 10; columnNum++)
{
int columnWidth = sheet.GetColumnWidth(columnNum) / 256;
for (int rowNum = 1; rowNum <= sheet.LastRowNum; rowNum++)
{
IRow currentRow = sheet.GetRow(rowNum);
if (currentRow.GetCell(columnNum) != null)
{
ICell currentCell = currentRow.GetCell(columnNum);
int length = Encoding.Default.GetBytes(currentCell.ToString()).Length;
if (columnWidth < length)
{
columnWidth = length;
}
}
}
sheet.SetColumnWidth(columnNum, columnWidth * 256);
}
workbook.Write(ms);
FileStream file = new FileStream(saveFileName, FileMode.Create);
workbook.Write(file);
file.Close();
workbook = null;
ms.Close();
ms.Dispose();
MessageBox.Show(fileName + " 保存成功", "提示", MessageBoxButtons.OK);
}