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

    最后效果:

  • 相关阅读:
    团购网站之大众点评
    cas xml
    smsUtil
    solr配置
    xml
    yu
    Schema.xml
    ApplicationContext-redis.xml
    fast
    第一版
  • 原文地址:https://www.cnblogs.com/Fred1987/p/10981549.html
Copyright © 2011-2022 走看看