How to use DataTable as ItemsSource of my DataGrid(如何将DataTable用作我的DataGrid的ItemsSource)

本文介绍了如何将DataTable用作我的DataGrid的ItemsSource的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要将Excel文件加载到我的DataGrid中。使用ClosedXML

我有这个方法:

public static DataTable ImportExceltoDataTable(string filePath, string sheetName) {

    using (XLWorkbook wb = new(filePath)) {

        IXLWorksheet ws = wb.Worksheet(1);
        DataTable dt = new();

        bool firstRow = true;
        foreach (IXLRow row in ws.Rows()) {

            if (firstRow) {
                foreach (IXLCell cell in row.Cells()) {
                    dt.Columns.Add(cell.CachedValue.ToString());
                }
                
                firstRow = false;

            } else {
      
                dt.Rows.Add();
                int i = 0;
          
                foreach (IXLCell cell in row.Cells(row.FirstCellUsed().Address.ColumnNumber, row.LastCellUsed().Address.ColumnNumber)) {
                
                    dt.Rows[dt.Rows.Count - 1][i} = cell.CachedValue.ToString();
                    i++;
                }
            }
        }
 
        return dt;
    }
}

这是我的点击事件:

OpenFileDialog of = new();
of.Filter = "Excel Files | *.xlsx;";
of.Title = "Import Excel file.";

if (of.ShowDialog()==true) {

    dataGrid.ItemsSource = ImportExceltoDataTable("...", "...").DefaultView;
}

我正在努力实现以下目标

  • 单击一个按钮,选择一个Excel文件,用其内容填充我的DataGrid

添加@MM8提供的解决方案后更新:

我现在收到Empty extension is not supported错误,因为我不知道如何将单击事件的OpenFileDialog选择连接到DataTable的启动。

非常感谢您的帮助!

推荐答案

可以将ItemsSource设置为DataTableDefaultView

dataGrid.ItemsSource = ImportExceltoDataTable("...", "...").DefaultView;

DataTable不同,DataView实现所需的IEnumerable接口。

这篇关于如何将DataTable用作我的DataGrid的ItemsSource的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!