using Autodesk.Revit.DB; using KDCS.Utils; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Excel = Microsoft.Office.Interop.Excel; namespace KMBIM { public partial class ExcelExport : System.Windows.Forms.Form { public Autodesk.Revit.DB.Document doc = null; // Store the reference of the application in revit Microsoft.Office.Interop.Excel.Application excelApp = null; Excel.Workbook workbook = null; public ExcelExport() { InitializeComponent(); } public ExcelExport(Autodesk.Revit.DB.Document revit_db) { InitializeComponent(); doc = revit_db; } private void Form1_Load(object sender, EventArgs e) { this.KeyPreview = true; tbPath.Text = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\" + doc.Title + ".xlsx"; FilteredElementCollector collector = new FilteredElementCollector(doc); IList collection = collector.OfClass(typeof(ViewSchedule)).ToElements(); ViewScheduleExportOptions op = new ViewScheduleExportOptions(); foreach (Element el in collection) { ViewSchedule viewSchedule = el as ViewSchedule; if (!viewSchedule.IsTitleblockRevisionSchedule) listBox1.Items.Add(viewSchedule.Name); } } public void getScheduleData(Document doc) { FilteredElementCollector collector = new FilteredElementCollector(doc); IList collection = collector.OfClass(typeof(ViewSchedule)).ToElements(); String prompt = "ScheduleData :"; prompt += Environment.NewLine; foreach (Element e in collection) { ViewSchedule viewSchedule = e as ViewSchedule; TableData table = viewSchedule.GetTableData(); TableSectionData section = table.GetSectionData(SectionType.Body); int nRows = section.NumberOfRows; int nColumns = section.NumberOfColumns; if (nRows > 1) { // valueData.Add(viewSchedule.Name); List> scheduleData = new List>(); for (int i = 0; i < nRows; i++) { List rowData = new List(); for (int j = 0; j < nColumns; j++) { rowData.Add(viewSchedule.GetCellText(SectionType.Body, i, j)); } scheduleData.Add(rowData); } List columnData = scheduleData[0]; scheduleData.RemoveAt(0); DataMapping(columnData, scheduleData); } } } public static void DataMapping(List keyData, List> valueData) { List> items = new List>(); string prompt = "Key/Value"; prompt += Environment.NewLine; foreach (List list in valueData) { for (int key = 0, value = 0; key < keyData.Count && value < list.Count; key++, value++) { Dictionary newItem = new Dictionary(); string k = keyData[key]; string v = list[value]; newItem.Add(k, v); items.Add(newItem); } } foreach (Dictionary item in items) { foreach (KeyValuePair kvp in item) { prompt += "Key: " + kvp.Key + ",Value: " + kvp.Value; prompt += Environment.NewLine; } } Autodesk.Revit.UI.TaskDialog.Show("Revit", prompt); } #region 버튼 기능 private void button2_Click(object sender, EventArgs e) { foreach (var item in listBox1.SelectedItems) { listBox2.Items.Add(item.ToString()); } for (int i = 0; i < listBox2.Items.Count; i++) { listBox1.Items.Remove(listBox2.Items[i].ToString()); } } private void button3_Click(object sender, EventArgs e) { foreach (var item in listBox2.SelectedItems) { listBox1.Items.Add(item.ToString()); } for (int i = 0; i < listBox1.Items.Count; i++) { listBox2.Items.Remove(listBox1.Items[i].ToString()); } } private void button1_Click(object sender, EventArgs e) { for (int i = 0; i < listBox1.Items.Count; i++) { listBox2.Items.Add(listBox1.Items[i].ToString()); } listBox1.Items.Clear(); } private void button4_Click(object sender, EventArgs e) { for (int i = 0; i < listBox2.Items.Count; i++) { listBox1.Items.Add(listBox2.Items[i].ToString()); } listBox2.Items.Clear(); } #endregion public void partExport(ViewSchedule schedule, SectionType type, Excel.Worksheet sheet, ref int nRow) { TableData table = schedule.GetTableData(); TableSectionData section = table.GetSectionData(type); if (section == null) return; int nRows = section.NumberOfRows; int nColumns = section.NumberOfColumns; if (nRows > 0) { for (int i = 0; i < nRows; i++) { List rowData = new List(); for (int j = 0; j < nColumns; j++) { TableCellStyle style = section.GetTableCellStyle(i, j); TableMergedCell mergecell = section.GetMergedCell(i, j); TableCellCalculatedValueData v = section.GetCellCalculatedValue(i, j); FormatOptions f = section.GetCellFormatOptions(i, j, doc); rowData.Add(schedule.GetCellText(type, i, j)); string strvalue = schedule.GetCellText(type, i, j); var cell = sheet.Cells[i + nRow, j + 1] as Excel.Range; // cell.Interior.Color = System.Drawing.Color.FromArgb(1,style.BackgroundColor.Red, style.BackgroundColor.Green, style.BackgroundColor.Blue); cell.Value = strvalue; cell.EntireColumn.ColumnWidth = Unit.FeetToMM(section.GetColumnWidth(j)); } } if (type == SectionType.Body) { Excel.Range oRng1 = (Excel.Range)sheet.Cells[nRow, 1]; // point two is the bottom, rightmost cell Excel.Range oRng2 = (Excel.Range)sheet.Cells[nRow + nRows, nColumns]; // define the actual range we want to select var oRng = sheet.Range[oRng1, oRng2]; oRng.Select(); // and select it oRng.Select(); // and select it oRng.Worksheet.ListObjects.AddEx(SourceType: Excel.XlListObjectSourceType.xlSrcRange, Source: oRng, XlListObjectHasHeaders: Excel.XlYesNoGuess.xlNo); } nRow += nRows - 1; } } private void btn_export_Click(object sender, EventArgs e) { if (tbPath.Text == "") { MessageBox.Show("엑셀 파일 경로 지정후 다시 시도하시기 바랍니다."); return; } string excelFile = tbPath.Text; FilteredElementCollector collector = new FilteredElementCollector(doc); IList collection = collector.OfClass(typeof(ViewSchedule)).ToElements(); try { if (collection.Count > 0) { //일람표가 하나라도 있으면 엑셀 오픈 하기 if (radioButton1.Checked) { excelApp = new Microsoft.Office.Interop.Excel.Application(); excelApp.Visible = false; //workbook = (Workbook)(excelApp.Workbooks.Add(System.Reflection.Missing.Value)); workbook = excelApp.Workbooks.Add(); } } else { //하나라도 없으면 일람표가 없다고 메시지 보여주고 끝내기 MessageBox.Show("일람표가 존재하지 않습니다. \n 기능을 종료합니다."); return; } for (int z = 0; z < listBox2.Items.Count; z++) { if (radioButton2.Checked) { excelApp = new Microsoft.Office.Interop.Excel.Application(); excelApp.Visible = false; workbook = excelApp.Workbooks.Add(); } string sheet_name = listBox2.Items[z].ToString(); ViewSchedule viewSchedule = null; foreach (Element el in collection) { if (el.Name.CompareTo(sheet_name) != 0) { continue; } viewSchedule = el as ViewSchedule; break; } Excel.Worksheet sheet1 = null; if (viewSchedule != null) { sheet1 = (Excel.Worksheet)workbook.Worksheets.Add(Type.Missing); //기본 시트 후에 생성 sheet1.Name = viewSchedule.Name; // sheet1.Columns.AutoFit(); } int nRow = 1; //헤더파트 partExport(viewSchedule, SectionType.Header, sheet1, ref nRow); //서머리 파트 partExport(viewSchedule, SectionType.Summary, sheet1, ref nRow); //바디파트 partExport(viewSchedule, SectionType.Body, sheet1, ref nRow); partExport(viewSchedule, SectionType.Footer, sheet1, ref nRow); if (radioButton2.Checked == true) { //엑셀 끝내기 string dir = System.IO.Path.GetDirectoryName(tbPath.Text); string file = System.IO.Path.GetFileNameWithoutExtension(tbPath.Text); string ext = System.IO.Path.GetExtension(tbPath.Text); string filename = sheet1.Name + ext; excelFile = System.IO.Path.Combine(dir, filename); workbook.SaveAs(excelFile); workbook.Close(true); excelApp.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp); excelApp = null; workbook = null; System.GC.Collect(); GC.WaitForPendingFinalizers(); } } if (radioButton1.Checked == true) { //엑셀 끝내기 workbook.SaveAs(excelFile); try { workbook.Close(true); } catch { } excelApp.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp); excelApp = null; workbook = null; System.GC.Collect(); GC.WaitForPendingFinalizers(); } } catch (Exception ex) { // workbook.Close(true); string msg = "Error:Could not open worksheet in " + ": " + ex.Message; excelApp.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp); excelApp = null; workbook = null; System.GC.Collect(); GC.WaitForPendingFinalizers(); throw new Exception(msg); } this.Close(); } private void btnPath_Click(object sender, EventArgs e) { SaveFileDialog saveFileDialog1 = new SaveFileDialog(); saveFileDialog1.Filter = "Excel Files(*.xlsx)|*.xlsx"; saveFileDialog1.FilterIndex = 2; saveFileDialog1.RestoreDirectory = true; if (saveFileDialog1.ShowDialog() == DialogResult.OK) { tbPath.Text = saveFileDialog1.FileName; } // FolderBrowserDialog dialog = new FolderBrowserDialog(); // dialog.ShowDialog(); // tbPath.Text = dialog.SelectedPath; } private void listBox1_DrawItem(object sender, DrawItemEventArgs e) { if (listBox1.Items.Count > 0) { e.DrawBackground(); StringFormat sf = new StringFormat(); sf.LineAlignment = StringAlignment.Center; sf.Alignment = StringAlignment.Near; e.Graphics.DrawString(this.listBox1.Items[e.Index].ToString(), e.Font, Brushes.Black, e.Bounds, sf); e.DrawFocusRectangle(); } } private void listBox2_DrawItem(object sender, DrawItemEventArgs e) { if(listBox2.Items.Count > 0) { e.DrawBackground(); StringFormat sf = new StringFormat(); sf.LineAlignment = StringAlignment.Center; sf.Alignment = StringAlignment.Near; e.Graphics.DrawString(this.listBox2.Items[e.Index].ToString(), e.Font, Brushes.Black, e.Bounds, sf); e.DrawFocusRectangle(); } } private void ExcelExport_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Escape) { this.DialogResult = DialogResult.Cancel; } else if (e.KeyCode == Keys.Enter) { this.DialogResult = DialogResult.OK; } } } }