我将excel中的数据提取到datatable
,然后提取到datagrid
。数据的格式类似于;
"Time","Dist","speed","susp","rpm"
"0.000","0","235","29","13550"
"0.005","1","240","28.5","13560"
"0.010","2","245","28","13570"
"0.015","3","250","27.5","13580"
"0.020","4","255","27","13590"
"0.025","5","260","26.5","13600"
"0.030","6","265","26","13610"
但是,我拥有的列数及其名称是事先未知的,并且会从数据集更改为数据集。
通过按钮点击事件(WPF)拉入数据;
private void databtn_Click(object sender, RoutedEventArgs e)
{
{
OpenFileDialog openfile = new OpenFileDialog();
openfile.DefaultExt = ".xlsx";
openfile.Filter = "(.xlsx)|*.xlsx";
var browsefile = openfile.ShowDialog();
if (browsefile == true)
{
datafilepath.Text = openfile.FileName;
ExcelEngine excelEngine = new ExcelEngine();
IApplication application = excelEngine.Excel;
application.DefaultVersion = ExcelVersion.Excel2013;
IWorkbook workbook = application.Workbooks.Open(datafilepath.Text);
IWorksheet worksheet = workbook.Worksheets[0];
DataTable dt = worksheet.ExportDataTable(worksheet.UsedRange, ExcelExportDataTableOptions.ColumnNames);
DG.ItemsSource = dt.DefaultView;
}
}
}
如何将每个列放入单独的值列表中,列表名称由列标题给出?
然后我将使用它们绘制x,y图表; (时间,转速)或(距离,转速) - 我可以这样做,但我似乎无法遍历datatable
或datagrid
中指定列中的值。
我是c#和编程的新手,对不起,如果这是初级的,请提前感谢您提供任何帮助。
答案 0 :(得分:3)
您可以将列表存储在Dictionary<string, List<object>>
:
Dictionary<string, List<object>> dict = dt.Columns.Cast<DataColumn>()
.ToDictionary(c => c.ColumnName, c => dt.AsEnumerable().Select(r => r[c]).ToList());
这是一个LINQ查询,因此您必须添加using System.Linq
。
输出:
foreach (var kv in dict)
Console.WriteLine($"Column: {kv.Key}, All values: {String.Join(",", kv.Value)}");