欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

NET npoi 保存文件

程序员文章站 2022-11-30 14:26:24
npoi完整代码: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);
            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;
        }