aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/Tango.Documents/ExcelWriter.cs
blob: 63c04bce95011db2501bff6619dfbd620974c179 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Tango.Documents
{
    public class ExcelWriter : IDisposable
    {
        private Stream _stream;
        private SpreadsheetDocument _document;
        private List<DefinedName> _column_names;

        public ExcelWriter(Stream source)
        {
            _stream = source;
            _document = SpreadsheetDocument.Open(_stream, true);
            _column_names = new List<DefinedName>();

            if (_document.WorkbookPart.Workbook.GetFirstChild<DefinedNames>() != null)
            {
                foreach (DefinedName name in _document.WorkbookPart.Workbook.GetFirstChild<DefinedNames>())
                {
                    _column_names.Add(name);
                }
            }
        }

        public ExcelWriter(String fileName) : this(new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite))
        {

        }

        public void WriteData<T>(IEnumerable<T> data, String sheetName)
        {
            var props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance).ToList();

            WorksheetPart work_sheet_part = GetWorkSheetPart(sheetName);
            Worksheet workSheet = work_sheet_part.Worksheet;
            SheetData sheetData = workSheet.GetFirstChild<SheetData>();
            List<Row> rows = sheetData.Elements<Row>().ToList();

            var list = data.ToList();

            for (int i = 0; i < list.Count; i++)
            {
                var item = list[i];

                var last_row = sheetData.Elements<Row>().Last();

                Row newRow = new Row();
                newRow.RowIndex = last_row.RowIndex + 1;

                sheetData.InsertAfter(newRow, last_row);

                foreach (var prop in props)
                {
                    var definedName = _column_names.SingleOrDefault(x => x.Name == prop.Name);

                    if (definedName != null)
                    {
                        SetCellRow(newRow, GetCellReference(definedName, i + 2), prop.GetValue(item));
                    }
                }
            }
        }

        private void SetCellRow(Row row, string cellReference, object value)
        {
            Cell cell = row.Descendants<Cell>().FirstOrDefault(c => c.CellReference == cellReference);
            if (cell == null)
            {
                cell = new Cell();
                cell.CellReference = cellReference;
            }
            cell.CellValue = new CellValue(value.ToString());

            cell.DataType = CellValues.Number;

            if (value is String)
            {
                cell.DataType = CellValues.String;
            }
            else if (value is DateTime)
            {
                cell.DataType = CellValues.Date;
            }
            else if (value is Boolean)
            {
                cell.DataType = CellValues.Boolean;
            }

            row.Append(cell);
        }

        private WorksheetPart GetWorkSheetPart(String sheetName)
        {
            var sheet = _document.WorkbookPart.Workbook.Descendants<Sheet>().FirstOrDefault(x => x.Name.Value == sheetName);
            string relId = sheet.Id;
            return (WorksheetPart)_document.WorkbookPart.GetPartById(relId);
        }

        private string GetCellReference(DefinedName name, int rowIndex)
        {
            Regex rowPatern = new Regex("^.*\\!\\$(.*)\\$\\d*$");
            Match match = rowPatern.Match(name.Text);
            return match.Groups[1].Value + rowIndex.ToString();
        }

        public void Dispose()
        {
            _document.Save();
            _stream.Dispose();
        }
    }
}