NET npoi 保存文件

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

            // FileStream
            using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))
            {
                book.Write(fs);
            }
            // MemoryStream
            MemoryStream ms = new MemoryStream();
            book.Write(ms);
            saveTofle(ms, filePath);
        }
复制代码

 获得workbook

复制代码
        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;
        }
复制代码

MemoryStream

复制代码
        private static void saveTofle(MemoryStream file, string filePath)// string fileName
        {
            //if (!Directory.Exists(filePath)) Directory.CreateDirectory(filePath);
            using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write))
            {
                byte[] buffer = file.ToArray();//转化为byte格式存储
                fs.Write(buffer, 0, buffer.Length);
                fs.Flush();
                buffer = null;
            }
        }
复制代码

 

posted @   Robot-Blog  阅读(1563)  评论(4编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示