Приложение для десериализации Xml файлов в Excel
20.10.2016, 17:54. Показов 834. Ответов 0
Хочется увидеть мнение или советы.
Делаю минисофтик, для одного знакомого.
Суть програмки:
Пользователь указывает папку, где лежат его xml файлы.
Порграмка - десериализует файлы и вставляет их в excel.
Логика такова:
Из эксель берутся данные с расходами и номерами телефонов сотрудников,
помимо указания xml директории, указывается макет excel, в который внесены номера телефонов с соответствующими им фамилиями. Програмка добавляет колонки с расходами по месяцам напротив этих фамилий.
Пока что не реализована часть задуманного, но она уже работает:
https://github.com/EveKS/Xml_To_Excel
В ближайшее время уберу лишние евенты, всё сведу к кнопке сохранить.
Ну и выложу пару классов сюда:
Утилити часть:
ReadXmlFoder
C# | 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
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;
using Xml2CSharp;
namespace Xml_To_Excel.Utility
{
public interface IReadXmlFoder
{
Task<IEnumerable<Bill>> Read(string directory, Encoding enc);
}
public class ReadXmlFoder : IReadXmlFoder
{
public async Task<IEnumerable<Bill>> Read(string directory, Encoding enc)
=> await Task.Run(() =>
{
return new DirectoryInfo(directory)
.EnumerateFiles("*.xml", SearchOption.AllDirectories)
.Select(fi =>
{
XmlSerializer formatter = new XmlSerializer(typeof(Bill));
string tmp = string.Empty;
using (StreamReader sr = new StreamReader(fi.FullName, enc))
{
tmp += sr.ReadToEndAsync().Result;
}
XmlDocument xDoc = new XmlDocument();
xDoc.LoadXml(tmp.Replace("\x0c", ""));
return DeserializeFromXmlDocument(xDoc).Result;
});
});
static async Task<Bill> DeserializeFromXmlDocument(XmlDocument doc)
=> await Task.Run(() =>
{
XmlSerializer seri = new XmlSerializer(typeof(Bill));
Bill bill;
using (var reader = new XmlNodeReader(doc.DocumentElement))
{
bill = (Bill)seri.Deserialize(reader);
}
return bill;
});
}
} |
|
ExcelManager
C# | 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
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Excel = Microsoft.Office.Interop.Excel;
namespace Xml_To_Excel.Utility
{
public class ExcelSelect
{
public string PathExelSelect { get; set; }
public string SelectInExelFrom { get; set; }
public string SelectInExelTo { get; set; }
}
public interface IExcelManager
{
Task<object[,]> ListExcelArrayMaker(ExcelSelect excelSelect);
}
public class ExcelManager : IExcelManager
{
public async Task<object[,]> ListExcelArrayMaker(ExcelSelect excelSelect)
=> await Task.Run(() =>
{
Excel.Application excel = new Excel.Application();
excel.Visible = false;
excel.Workbooks.Open(excelSelect.PathExelSelect);
var exc = (object[,])excel
.Range[excelSelect.SelectInExelFrom + ":"
+ excelSelect.SelectInExelTo].Value;
excel.Quit();
return exc;
});
}
} |
|
ExcelMaker
C# | 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
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Excel = Microsoft.Office.Interop.Excel;
using Xml2CSharp;
using System.Globalization;
namespace Xml_To_Excel.Utility
{
public class ExcelData
{
DateTime _date;
public DateTime Date
{
get { return _date; }
set { _date = value; }
}
public string[,] Excel { get; set; }
}
public interface IExcelMaker
{
void ToMakeExcel(Task<IEnumerable<Bill>> xmls, Task<object[,]> excel);
}
public class ExcelMaker : IExcelMaker
{
public async void ToMakeExcel(Task<IEnumerable<Bill>> xmls, Task<object[,]> excel)
=> await Task.Run( async() =>
{
#region XmlToArray
var _xmls = await xmls;
var xmlData = _xmls.Select(xml =>
{
ExcelData ExcelData = new ExcelData();
ExcelData.Date = DateTime.Parse(xml.Title.B_start, null, DateTimeStyles.RoundtripKind);
var temp = xml.Ch_details.Charges_d.Charge_d.Select(d =>
new { call = d.C_num, tot = d.C_tot }).ToArray();
string[,] arrXml = new string[temp.Length, 2];
for (int i = 0; i < arrXml.GetUpperBound(0); i++)
{
arrXml[i, 0] = temp[i].call;
arrXml[i, 1] = temp[i].tot;
}
ExcelData.Excel = arrXml;
return ExcelData;
}).OrderBy(xml=>xml.Date).ToList();
#endregion
#region ToExcel
var excalResult = excel.Result;
for (int i = 4; i < xmlData.Count + 4; i++)
{
excalResult = Sorts(excalResult, xmlData[i - 4].Excel, i);
}
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWb;
Excel.Worksheet xlSht;
//var abs = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
xlWb = xlApp.Workbooks.Add(System.Reflection.Missing.Value);
xlSht = (Excel.Worksheet)xlWb.Sheets[1];
xlSht.Range["A1"]
.Resize[excalResult.GetUpperBound(0), excalResult.GetUpperBound(1)]
.Value = excalResult;
var excelDate = xmlData.Select(xml => xml.Date.ToString("MMM.yyyy")).ToArray();
xlSht.Range["D2"].Resize[1, excelDate.Length].Value = excelDate;
xlSht.Columns["B:Z"].AutoFit();
xlWb.Close(true);
xlApp.Quit();
#endregion
});
public static object[,] Sorts(object[,] arrExcel, string[,] arrXml, int n)
{
for (int i = 1; i <= arrExcel.GetLength(0); i++)
for (int j = 0; j < arrXml.GetLength(0); j++)
if (arrExcel[i, 2]?.ToString().Trim() == arrXml[j, 0]?.Trim().Substring(2))
{
arrExcel[i, n] = arrXml[j, 1];
}
return arrExcel;
}
}
} |
|
FileManager
C# | 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
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Xml_To_Excel.Utility
{
public interface IFileManager
{
bool IsExist(string filePath);
bool IsFolderExist(string filePath);
Task GetExcel(string filePath, string xmlsPath);
Task MakeExcel(string excelPath, string xmlsPath, Encoding encoding);
}
public class FileManager : IFileManager
{
private readonly IExcelMaker _excelMaker;
private readonly IReadXmlFoder _readXmlFolder;
private readonly IExcelManager _excelManager;
public FileManager() : this(new ExcelMaker(), new ReadXmlFoder(), new ExcelManager())
{ }
FileManager(IExcelMaker excelMaker, IReadXmlFoder readXmlFolder, IExcelManager excelManager)
{
_excelMaker = excelMaker;
_readXmlFolder = readXmlFolder;
_excelManager = excelManager;
}
private readonly Encoding _dafaultEncoding = Encoding.UTF8;
public bool IsExist(string filePath)
{
bool isExist = File.Exists(filePath);
return isExist;
}
public bool IsFolderExist(string folderPath)
{
bool isExist = Directory.Exists(folderPath);
return isExist;
}
public async Task GetExcel(string filePath, string xmlsPath)
{
await MakeExcel(filePath, xmlsPath, _dafaultEncoding);
}
public async Task MakeExcel(string excelPath, string xmlsPath, Encoding encoding)
=> await Task.Run(() =>
{
ExcelSelect ExcelSelect = new ExcelSelect();
ExcelSelect.PathExelSelect = excelPath;
ExcelSelect.SelectInExelFrom = "A1";
ExcelSelect.SelectInExelTo = "Z500";
var a = _excelManager.ListExcelArrayMaker(ExcelSelect);
var b = _readXmlFolder.Read(xmlsPath, encoding);
_excelMaker.ToMakeExcel(b, a);
});
}
} |
|
Presenter:
MainPresenter
C# | 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
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xml_To_Excel.Services;
using Xml_To_Excel.Utility;
namespace Xml_To_Excel.Presenter
{
public class MainPresenter
{
private readonly IMainForm _view;
private readonly IFileManager _meneger;
private readonly IMessageService _messegeService;
private string _currentExcelFilePath;
private string _currentXmlFolderPath;
public MainPresenter(IMainForm view, IFileManager manager, IMessageService service)
{
_view = view;
_meneger = manager;
_messegeService = service;
_view.SelectExel += _view_SelectExel;
_view.SelectXml += _view_SelectXml;
_view.Save += _view_Save;
}
private void _view_SelectExel(object sender, EventArgs e)
{
try
{
string exelPath = _view.SelectExelPath;
bool isExist = _meneger.IsExist(exelPath);
if (!isExist)
{
_messegeService.ShowExclamation("Выбранный фаил не существует.");
return;
}
_currentExcelFilePath = exelPath;
}
catch (Exception ex)
{
_messegeService.ShowError(ex.Message);
}
}
private void _view_SelectXml(object sender, EventArgs e)
{
try
{
string xmlsPath = _view.SelectXmlFolderPath;
bool isFolderExist = _meneger.IsFolderExist(xmlsPath);
if (!isFolderExist)
{
_messegeService.ShowExclamation("Выбранная папка не существует.");
return;
}
_currentXmlFolderPath = xmlsPath;
}
catch (Exception ex)
{
_messegeService.ShowError(ex.Message);
}
}
private async void _view_Save(object sender, EventArgs e)
{
try
{
await _meneger.GetExcel(_currentExcelFilePath, _currentXmlFolderPath);
}
catch (Exception ex)
{
_messegeService.ShowError(ex.Message);
}
}
}
} |
|
Временный метод
Временная "заплатка" в моем FileManager =)
Сделал чтобы связать с визуалкой.
C# | 1
2
3
4
5
6
7
8
9
10
11
| public async Task MakeExcel(string excelPath, string xmlsPath, Encoding encoding)
=> await Task.Run(() =>
{
ExcelSelect ExcelSelect = new ExcelSelect();
ExcelSelect.PathExelSelect = excelPath;
ExcelSelect.SelectInExelFrom = "A1";
ExcelSelect.SelectInExelTo = "Z500";
var a = _excelManager.ListExcelArrayMaker(ExcelSelect);
var b = _readXmlFolder.Read(xmlsPath, encoding);
_excelMaker.ToMakeExcel(b, a);
}); |
|
0
|