我正在用C#开发一个Windows 窗体应用程序。我的程序将从 excel 单元格中读取值并将数据插入 DataGridView 以显示用户。
在我阅读了 excel 文件后,我得到了字符串数组中的结果。如何插入 DataGridView?
private void btnImport_Click(object sender, EventArgs e)
{
Microsoft.Office.Interop.Excel.Application ExcelObj = null;
ExcelObj = new Microsoft.Office.Interop.Excel.Application();
if (ExcelObj != null)
{
if (tbxFileDirectory.Text != "")
{
Workbook workbook = ExcelObj.Workbooks.Open(
openFD.FileName, 0, true, 5, "", "", true, XlPlatform.xlWindows, "\t", false, false, 0, true);
Sheets sheets = workbook.Worksheets;
//Get excel sheet number
Worksheet worksheet = (Worksheet)sheets.get_Item(1);
for (int i = 6; i <= worksheet.UsedRange.Rows.Count; i++)
{
Range range = worksheet.get_Range("A" + i.ToString(), "K" + i.ToString());
Array myvalues = (Array)range.Cells.Value;
string[] strArray = ConvertToStringArray(myvalues);
//INSERT INTO DATAGRIDVIEW
}
MessageBox.Show("File was imported successfully");
}
else
{
MessageBox.Show("Please select the file to import.");
}
}
else
{
MessageBox.Show("ERROR: EXCEL couldn't be started!");
}
}
我的 DataGrid 有 4 列,ProductID、ProductName、Price 和 Qty。我想在每一列中插入这些值 strArray[0]、strArray[1]、strArray[9] 和 strArray[10]。我怎样才能做到这一点?任何帮助都感激不尽!