0
我有簡單的應用程序,我從excel文件導入數據到數據網格。這裏是代碼:刷新數據網格wpf。 ItemsSource和Items.Refresh()不起作用
private void InitializeDataGridView()
{
//Open the Excel file using ClosedXML.
using (XLWorkbook workBook = new XLWorkbook(ExcelFile.ExcelFilePath))
{
//Read the first Sheet from Excel file.
IXLWorksheet workSheet = workBook.Worksheet(1);
//Create a new DataTable.
DataTable dt = new DataTable();
//Loop through the Worksheet rows.
bool firstRow = true;
foreach (IXLRow row in workSheet.Rows())
{
//Use the first row to add columns to DataTable.
if (firstRow)
{
foreach (IXLCell cell in row.Cells())
{
dt.Columns.Add(cell.Value.ToString());
}
firstRow = false;
}
else
{
//Add rows to DataTable.
dt.Rows.Add();
int i = 0;
foreach (IXLCell cell in row.Cells())
{
dt.Rows[dt.Rows.Count - 1][i] = cell.Value.ToString();
i++;
}
}
dtGrid.ItemsSource = dt.DefaultView;
}
}
}
它工作正常。但我想添加一些數據。我使用這個代碼:
public static void AddData(DateTime date, int time, string title, string description)
{
// Opening excel file
using (XLWorkbook workBook = new XLWorkbook(ExcelFile.ExcelFilePath))
{
IXLWorksheet worksheet = workBook.Worksheet("Progress"); // Trying to get the Progress worksheet
// Getting table from DataTable
var dataTable = GetTable(date, time, title, description);
// Searching for last used row and first used column
var lastRowUsed = worksheet.LastRowUsed().RowNumber();
var firstColumnUsed = worksheet.FirstColumnUsed().ColumnNumber();
// Insterting data
worksheet.Cell(lastRowUsed + 1, firstColumnUsed).InsertData(dataTable.AsEnumerable());
// Adjusting content to fit
worksheet.Columns().AdjustToContents();
// Saving excel file
workBook.Save();
}
}
public static DataTable GetTable(DateTime date, int time, string title, string description)
{
DataTable table = new DataTable();
table.Columns.Add("Data", typeof(DateTime));
table.Columns.Add("Czas(minuty)", typeof(int));
table.Columns.Add("Tytuł", typeof(string));
table.Columns.Add("Opis", typeof(string));
table.Rows.Add(date, time, title, description);
return table;
}
它的工作正常。我的數據網格有問題。它沒有更新後,我添加到Excel文件。
我試圖做這樣的事情:
dtGrid.ItemsSource = null;
InitializeDataGridView();
它不是工作。我也用dtGrid.Items.Refresh();
,它沒有工作。 將數據添加到excel文件後,如何刷新我的數據網格?
你是否檢查過,編輯完你的excel過程後肯定是關閉的,即你看不到在任務管理器中運行的任何excel過程?如果你的文件仍然打開,那麼重新初始化你的網格可能不起作用 –
是的,我的excel文件肯定是關閉的。剛剛初始化之後,並在向其中添加一些數據之後。 – Porqqq
「進度」表與「WorkSheet(1)」相同嗎? – Crowcoder