using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Windows; using Autodesk.Revit.DB; using Autodesk.Revit.DB.Architecture; using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input; using EPPlus.Core.Extensions; using OfficeOpenXml; using OfficeOpenXml.Style; namespace RevitAddins { public partial class MainViewModel : ObservableObject { private readonly Autodesk.Revit.ApplicationServices.Application application; [ObservableProperty] [NotifyCanExecuteChangedFor(nameof(ExportExcelCommand))] private FileInfo selectedFileInfo; [ObservableProperty] private Dictionary excelTemplates; public MainViewModel(Autodesk.Revit.ApplicationServices.Application application) { this.ExcelTemplates = new Dictionary(); if (Directory.Exists(Path.Combine(GlobalVariables.DirAssembly, "Templates"))) { DirectoryInfo directoryInfo = new DirectoryInfo(Path.Combine(GlobalVariables.DirAssembly, "Templates")); var files = directoryInfo.GetFiles("*.xlsx"); foreach (var item in files) { ExcelTemplates.Add(item.Name, item); } } this.application = application; } private bool CanExport() { if (SelectedFileInfo == null) { return false; } return true; } [RelayCommand(CanExecute = nameof(CanExport))] private void ExportExcel() { StringBuilder sb = new StringBuilder(); //选择文件夹,并获取文件夹内的所有*.rvt文件 var folderDialog = new FolderBrowserDialog() { Multiselect = false }; if (folderDialog.ShowDialog() == false) { return; } var path = folderDialog.SelectedPath; if (Directory.Exists(path)) { DirectoryInfo directoryInfo = new DirectoryInfo(path); var files = directoryInfo.GetFiles("*.rvt"); foreach (var file in files) { Document document = null; try { document = application.OpenDocumentFile(file.FullName); var groups = document.OfParentModelCollector().WhereElementIsNotElementType() .GroupBy(e => e.GetParameters("深圳构件标识").FirstOrDefault().AsString()); var targetExcelPath = Path.Combine(path, Path.GetFileNameWithoutExtension(document.PathName) + ".xlsx"); var fileInfo = SelectedFileInfo.CopyTo(targetExcelPath, true); using var pkg = new ExcelPackage(fileInfo); var sheetToDel = new List(); foreach (var worksheet in pkg.Workbook.Worksheets) { var elements = groups.FirstOrDefault(g => g.Key == worksheet.Name)?.ToList(); if (worksheet.Name == "房间") { elements = [.. document.OfCollector().OfCategory(BuiltInCategory.OST_Rooms).Cast().Where(r => r.Area > 0)]; } if (elements == null || elements.Count == 0) { sheetToDel.Add(worksheet); continue; } // 获取到第三行的所有单元格的值,转成列号和值的字典 var range = worksheet.Cells[3, 1, 3, worksheet.Dimension.End.Column]; var values = new Dictionary(); foreach (var cell in range) { if (cell.Value != null) { values[cell.Start.Column] = cell.Text; } } for (var i = 0; i < elements.Count; i++) { var element = elements[i]; var row = 4 + i; foreach (var item in values) { var parameter = element.GetParameters(item.Value)?.FirstOrDefault(p => p.HasValue); if (parameter != null) { string value = string.Empty; switch (parameter.StorageType) { case StorageType.None: break; case StorageType.Integer: value = parameter.AsInteger().ToString(); break; case StorageType.Double: value = parameter.AsValueString(); break; case StorageType.String: //Revit数据库存储的值 var str = parameter.AsString(); if (string.IsNullOrEmpty(str)) { //用户可见的前端显示,如根据单位设置而显示的值 value = parameter.AsValueString(); } else { value = str; } break; case StorageType.ElementId: value = parameter.AsElementId().ToString(); break; } worksheet.Cells[row, item.Key].Value = value; //单元格宽度自适应 worksheet.Cells[row, item.Key].AutoFitColumns(); //单元格样式,边框线,水平居中 worksheet.Cells[row, item.Key].Style.Border.BorderAround(ExcelBorderStyle.Thin); worksheet.Cells[row, item.Key].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center; } //else //{ // MessageBox.Show($"参数{item}不存在!", "提示", MessageBoxButton.OK, MessageBoxImage.Warning); //} } } } foreach (var item in sheetToDel) { pkg.Workbook.Worksheets.Delete(item); } pkg.Save(); if (document != null) { document.Close(false); } //var package = Items // .ToWorksheet("参数表") // .WithConfiguration(cfg => cfg.WithColumnConfiguration(c => c.AutoFit())) // .ToExcelPackage(); } catch (Exception ex) { if (document != null) { document.Close(false); } sb.AppendLine(ex.Message); sb.AppendLine(ex.StackTrace); } } if (sb.Length > 0) { MessageBox.Show(sb.ToString()); } var result = MessageBox.Show( "是否打开文件夹?", "提示", MessageBoxButton.YesNo, MessageBoxImage.Question); if (result == MessageBoxResult.Yes) { Process.Start(path); } } } } }