.NET使用NPOI从datagridview导出excel

NPOI是指构建在POI 3.x版本之上的一个程序,NPOI可以在没有安装Office的情况下对Word或Excel文档进行读写操作。
NPOI是一个开源的C#读写Excel、WORD等微软OLE2组件文档的项目。

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);
}

posted @ 2020-05-13 14:01  天空之上、只有蓝黑  阅读(385)  评论(0编辑  收藏  举报