就我而言,我使用 Microsoft.Office.Interop.Excel 加载 excel 文件。我保存在数据表中以便在我的项目中重复使用,而无需再次从 datagridview 重新加载数据。
using Excel = Microsoft.Office.Interop.Excel;
Excel.Application excelApp = new Excel.Application();
public void LoadDataGridView(DataGridView dataGridView, DataTable dataTable)
{
if (excelApp != null)
{
Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(parentPath + @"\test.xlsx", 0, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
Excel.Worksheet excelWorksheet = (Excel.Worksheet)excelWorkbook.Sheets[1];
Excel.Range excelRange = excelWorksheet.UsedRange;
int rowCount = excelRange.Rows.Count;
int colCount = excelRange.Columns.Count;
DataRow row = null;
for (int i = 1; i <= rowCount; i++)
{
if (i != 1)
row = dataTable.NewRow();
for (int j = 1; j <= colCount; j++)
{
if (i == 1)
dataTable.Columns.Add(excelRange.Cells[1, j].value);
else
{
if(!String.IsNullOrEmpty(excelRange.Cells[i, 1].value2.ToString()))
{
row[j - 1] = excelRange.Cells[i, j].value;
}
}
}
if (row != null && !String.IsNullOrEmpty(row[@"Id"].ToString()))
dataTable.Rows.Add(row);
}
dataGridView.DataSource = dataTable;
excelWorkbook.Close();
excelApp.Quit();
}
}