zoukankan      html  css  js  c++  java
  • .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);
    }

  • 相关阅读:
    JS判断单选框是否选中
    Js判断是否有属性
    判断是否有焦点
    Js 替代
    Js解析json
    回车事件
    js解析XML
    Linux常用基础(三)
    Linux常用基础(二)
    Linux常用基础(一)
  • 原文地址:https://www.cnblogs.com/tuxer/p/12881990.html
Copyright © 2011-2022 走看看