zoukankan      html  css  js  c++  java
  • DataGridView数据用NPOI导出到Excel

    /// <summary>
    /// DataGridView数据用NPOI导出到Excel
    /// </summary>
    /// <param name="fileName">Excel文件名</param>
    /// <param name="dgv">DataGridView数据</param>
    public static void GridToExcel(string fileName, DataGridView dgv)
    {
    if (dgv.Rows.Count == 0)
    {
    return;
    }
    SaveFileDialog sfd = new SaveFileDialog();
    sfd.Filter = "Excel 2003格式|*.xls";
    sfd.FileName = fileName + DateTime.Now.ToString("yyyyMMddHHmmssms");
    if (sfd.ShowDialog() != DialogResult.OK)
    {
    return;
    }
    HSSFWorkbook wb = new HSSFWorkbook();
    ISheet sheet = wb.CreateSheet(fileName);
    IRow headRow = sheet.CreateRow(0);
    for (int i = 0; i < dgv.Columns.Count; i++)
    {
    headRow.CreateCell(i).SetCellValue(dgv.Columns[i].HeaderText);
    }
    for (int i = 0; i < dgv.Rows.Count; i++)
    {
    IRow row = sheet.CreateRow(i + 1);
    for (int j = 0; j < dgv.Columns.Count; j++)
    {
    ICell cell = row.CreateCell(j);
    if (dgv.Rows[i].Cells[j].Value == DBNull.Value)
    {
    cell.SetCellType(CellType.Blank);
    }
    else
    {
    if (dgv.Rows[i].Cells[j].ValueType.FullName.Contains("System.Int32"))
    {
    cell.SetCellValue(Convert.ToInt32(dgv.Rows[i].Cells[j].Value));
    }
    else if (dgv.Rows[i].Cells[j].ValueType.FullName.Contains("System.String"))
    {
    cell.SetCellValue(dgv.Rows[i].Cells[j].Value.ToString());
    }
    else if (dgv.Rows[i].Cells[j].ValueType.FullName.Contains("System.Single"))
    {
    cell.SetCellValue(Convert.ToSingle(dgv.Rows[i].Cells[j].Value));
    }
    else if (dgv.Rows[i].Cells[j].ValueType.FullName.Contains("System.Double"))
    {
    cell.SetCellValue(Convert.ToDouble(dgv.Rows[i].Cells[j].Value));
    }
    else if (dgv.Rows[i].Cells[j].ValueType.FullName.Contains("System.Decimal"))
    {
    cell.SetCellValue(Convert.ToDouble(dgv.Rows[i].Cells[j].Value));
    }
    else if (dgv.Rows[i].Cells[j].ValueType.FullName.Contains("System.DateTime"))
    {
    cell.SetCellValue(Convert.ToDateTime(dgv.Rows[i].Cells[j].Value).ToString("yyyy-MM-dd"));
    }
    }
    }

    }
    for (int i = 0; i < dgv.Columns.Count; i++)
    {
    sheet.AutoSizeColumn(i);//自动列宽

    }
    using (FileStream fs = new FileStream(sfd.FileName, FileMode.Create))
    {
    wb.Write(fs);
    }
    //成功提示
    if (MessageBox.Show("导出成功,是否立即打开?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
    {
    System.Diagnostics.Process.Start(sfd.FileName);
    }


    }

  • 相关阅读:
    Python学习之路(一)之Python基础1
    【第十一课】Tomcat原理解析【转】
    【第十课】Tomcat入门
    【第九课】MriaDB密码重置和慢查询日志
    【第八课】php-fpm.conf配置文件解析
    【第七课】Nginx反向代理和负载均衡
    【第六课】Nginx常用配置下详解
    maven项目中更新了核心库后导致一些包提示未定义,如:The import org.json cannot be resolved
    js代码突然在花括号回车自动多加了一个大括号
    SQL0419N 十进制除法运算无效,因为结果将有一个负小数位。 SQLSTATE=42911
  • 原文地址:https://www.cnblogs.com/wwwlzp/p/13596691.html
Copyright © 2011-2022 走看看