101 lines
3.2 KiB
C#
101 lines
3.2 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Reflection;
|
|
using System.Windows.Forms;
|
|
using dezentrale.model;
|
|
|
|
namespace dezentrale.view
|
|
{
|
|
public class frmExportCsv<T> : FormWithActionButtons
|
|
{
|
|
private List<T> list;
|
|
private LvSelectFields lv;
|
|
|
|
private bool ExportCsv(List<string> properties)
|
|
{
|
|
SaveFileDialog sfd = new SaveFileDialog(){
|
|
FileName = $"{typeof(T)}_{list.Count}_items.csv",
|
|
Filter = "Comma-Separated-Value files (*.csv)|*.csv"
|
|
};
|
|
DialogResult dr = sfd.ShowDialog();
|
|
if (dr != DialogResult.OK)
|
|
return false;
|
|
|
|
try
|
|
{
|
|
CsvFile csv = new CsvFile() {
|
|
|
|
};
|
|
|
|
//Build headline
|
|
csv.FileContents.Add(properties);
|
|
|
|
foreach (T t in list)
|
|
{
|
|
List<string> t_csv = new List<string>();
|
|
foreach (string p in properties)
|
|
{
|
|
//Get propertyinfo from T
|
|
PropertyInfo pi = typeof(T).GetProperty(p);
|
|
if (!pi.CanRead) continue;
|
|
try
|
|
{
|
|
object o = pi.GetValue(t, null);
|
|
string propVal = (o == null ? "null" : o.ToString());
|
|
t_csv.Add(propVal);
|
|
} catch(Exception ex)
|
|
{
|
|
t_csv.Add(ex.Message);
|
|
}
|
|
}
|
|
csv.FileContents.Add(t_csv);
|
|
}
|
|
csv.SaveFile(sfd.FileName);
|
|
} catch(Exception ex)
|
|
{
|
|
MessageBox.Show($"Error({ex.GetType()}):\r\n{ex.Message}");
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
private void BuildGui()
|
|
{
|
|
this.Text = $"Export {list.Count} of \"{typeof(T).ToString()}\"";
|
|
|
|
this.Controls.Add(lv = new LvSelectFields()
|
|
{
|
|
Left = 0,
|
|
Width = this.ClientSize.Width,
|
|
Top = 0,
|
|
Height = this.ClientSize.Height - 60,
|
|
Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Bottom | AnchorStyles.Right,
|
|
});
|
|
|
|
foreach (var p in typeof(T).GetProperties())
|
|
{
|
|
lv.AddEntry(p.Name);
|
|
}
|
|
|
|
this.AddButton("All fields", (sender, e) => {
|
|
List<string> all = lv.GetAllItems();
|
|
if (ExportCsv(all)) this.Close();
|
|
});
|
|
this.AddButton("Selected fields", (sender, e) => {
|
|
List<string> selected = lv.GetSelectedItems();
|
|
if (ExportCsv(selected)) this.Close();
|
|
});
|
|
this.AddButton("Cancel", (sender, e) => { this.Close(); });
|
|
}
|
|
|
|
public frmExportCsv(T t)
|
|
{
|
|
list = new List<T> { t };
|
|
BuildGui();
|
|
}
|
|
public frmExportCsv(List<T> l)
|
|
{
|
|
list = l;
|
|
BuildGui();
|
|
}
|
|
}
|
|
} |