目录

    IFC 输出Excel 空间报告文件

   本示例将展示从IFC文件读取数据所需的一些概念。它使用IFC4 接口,可以同时用于IFC2x3和IFC4版本。创建EXCEL文件,我们使用开源的组件NPOI。这个例子只需要xBIM Essentials。

 引用命名空间:

using NPOI.SS.UserModel;   // EXCEL 组件
using NPOI.XSSF.UserModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using Xbim.Ifc;
using Xbim.Ifc4.Interfaces;

主要的功能如下所示:

//从模板初始化NPOI工作簿
var workbook = new XSSFWorkbook("template.xlsx");
var sheet = workbook.GetSheet("Spaces");//用单位创建漂亮的数字格式。 现实中需要更多的关心的是单位。
//我们只知道我们现在的模型有空间面积以立方米和空间体积为单位
//请注意从Revit导出的原始数据是错误的,因为数据量比应该大1000倍。
//在这个例子中,数据是使用xBIM修复的。
var areaFormat = workbook.CreateDataFormat();
var areaFormatId = areaFormat.GetFormat("# ##0.00 [$m²]");
var areaStyle = workbook.CreateCellStyle();
areaStyle.DataFormat = areaFormatId;
var volumeFormat = workbook.CreateDataFormat();
var volumeFormatId = volumeFormat.GetFormat("# ##0.00 [$m³]");
var volumeStyle = workbook.CreateCellStyle();
volumeStyle.DataFormat = volumeFormatId;
//打开IFC模型。 不会改变模型中的任何东西,所以我们可以把编辑器的信息保留下来。
using (var model = IfcStore.Open("SampleHouse.ifc"))
{
    //获取模型中的所有空间. 
    //需要 ToList() 方便使用 Foreach
    var spaces = model.Instances.OfType<IIfcSpace>().ToList();
    //设置报表标题
    sheet.GetRow(0).GetCell(0)
        .SetCellValue($"Space Report ({spaces.Count} spaces)");
    foreach (var space in spaces)
    {
        //写报表数据
        WriteSpaceRow(space, sheet, areaStyle, volumeStyle);
    }
}
//保存 报表
using (var stream = File.Create("spaces.xlsx"))
{
    workbook.Write(stream);
    stream.Close();
}
//打开保存的EXCEL 文件
Process.Start("spaces.xlsx");

从IFC 读取数据,并为每个空间写一行

private static void WriteSpaceRow(IIfcSpace space, ISheet sheet, ICellStyle areaStyle, ICellStyle volumeStyle)
{
    var row = sheet.CreateRow(sheet.LastRowNum + 1);

    var name = space.Name;
    row.CreateCell(0).SetCellValue(name);

    var floor = GetFloor(space);
    row.CreateCell(1).SetCellValue(floor?.Name);

    var area = GetArea(space);
    if (area != null)
    {
        var cell = row.CreateCell(2);
        cell.CellStyle = areaStyle;
        //如果来自于其他的类型 不保证是数字 (如财产 等)
        if (area.UnderlyingSystemType == typeof(double))
            cell.SetCellValue((double)(area.Value));
        else
            cell.SetCellValue(area.ToString());
    }

    var volume = GetVolume(space);
    if (volume != null)
    {
        var cell = row.CreateCell(3);
        cell.CellStyle = volumeStyle;
        if (volume.UnderlyingSystemType == typeof(double))
            cell.SetCellValue((double)(volume.Value));
        else
            cell.SetCellValue(volume.ToString());
    }
}
WriteSpaceRow

相关文章: