NET npoi 保存文件

2018-12-04 07:06:31来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

npoi完整代码:NET npoi帮助类

 

        public static void DataTableToExcel(List<DataTable> dataTables, string filePath)
        {
            if (dataTables == null || !dataTables.Any())
                throw new Exception("dataTables不能为null");
            bool isOldThan2007 = Path.GetExtension(filePath)?.ToLower() == ".xls";
            IWorkbook book = dataTables.ToWorkbook(isOldThan2007);
            using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))
            {
                book.Write(fs);
            }
        }

 

        public static IWorkbook ToWorkbook(this List<DataTable> dataTables, bool isOldThan2007)
        {
            IWorkbook book = isOldThan2007 ? new HSSFWorkbook() : (IWorkbook)new XSSFWorkbook();
            foreach (var dataTable in dataTables)
            {
                if (dataTable == null)
                    continue;
                ISheet sheet = book.CreateSheet(dataTable.TableName);
                IRow headerRow = sheet.CreateRow(0);
                foreach (DataColumn column in dataTable.Columns)
                {
                    headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
                }

                for (int i = 0; i < dataTable.Rows.Count; i++)
                {
                    DataRow row = dataTable.Rows[i];
                    IRow dataRow = sheet.CreateRow(i + 1);
                    for (int j = 0; j < dataTable.Columns.Count; j++)
                    {
                        dataRow.CreateCell(j).SetCellValue(row[j]?.ToString());
                    }
                }
            }
            return book;
        }

 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:把list集合的内容写入到Xml中,通过XmlDocument方式写入Xml文件

下一篇:NET 获取实例所表示的日期是星期几