zoukankan      html  css  js  c++  java
  • C# NPOI Export DataTable C# NPOI导出DataTable 单元格自适应大小

    1.Install-Package NPOI -v 2.4.0 

    2.

    using NPOI.XSSF;
    using NPOI.XSSF.UserModel;
    using NPOI.SS.UserModel;
    using System.IO; 
    static void ExportDataTable(DataTable dt)
            {
                string exportedExcelFullName = Directory.GetCurrentDirectory() + "//" + DateTime.Now.ToString("yyyyMMddHHmmssffff") + ".xlsx";
                if(dt!=null && dt.Rows.Count>0)
                {
                    XSSFWorkbook workBook = new XSSFWorkbook();
                    ISheet firstSheet = workBook.CreateSheet("First Sheet");
                    IRow headerRow = firstSheet.CreateRow(0);
                   
                    for(int i=0;i<dt.Columns.Count;i++)
                    {                    
                        ICell headerCell = headerRow.CreateCell(i);
                        headerCell.SetCellValue(dt.Columns[i].ColumnName?.ToString());                     
                    }                
    
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        IRow dataRow = firstSheet.CreateRow(i + 1);
                        for(int j=0;j<dt.Columns.Count;j++)
                        {
                            ICell dataCell = dataRow.CreateCell(j);                        
                            dataCell.SetCellValue(dt.Rows[i][j]?.ToString());                        
                        }
                    }
                    for(int i=0;i<dt.Columns.Count;i++)
                    {
                        firstSheet.AutoSizeColumn(i);
                    }                
    
                    using (FileStream excelStream = File.Create(exportedExcelFullName))
                    {
                        workBook.Write(excelStream);
                    } 
                }           
            }

    3.让Excel单元格自适应单元格大小

    for(int i=0;i<dt.Columns.Count;i++)
    {
    firstSheet.AutoSizeColumn(i);
    }

    最后效果:

  • 相关阅读:
    python 单下划线/双下划线使用总结
    error connection reset by peer 104
    变形课
    求并联电阻值
    HDU2054:A == B ?
    Do the Untwist
    开门人和关门人
    关于HEXO安装失败的解决方法
    代码高亮显示——google-code-prettify
    网站图标——favicon
  • 原文地址:https://www.cnblogs.com/Fred1987/p/10981549.html
Copyright © 2011-2022 走看看