我一直试图弄清楚如何将数组值添加到 DataGridView 中。就目前而言,所有值都被添加到单个列中,当我真的在寻找类似以下内容时:
Col1 Col2
Name Number
Adam 3
Ryan 4
现在他们显示为
Col1 Col2
Name
Number
Adam
3
Ryan
4
通过读取 excel 电子表格的值来填充数组。我已经搜索并尝试了不同的方法,但没有成功。这是我目前正在使用的代码。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
namespace WindowsFormsApplication12
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Excel.Application xlApp ;
Excel.Workbook xlWorkBook ;
Excel.Worksheet xlWorkSheet ;
Excel.Range range ;
//string str;
int rCnt = 0;
int cCnt = 0;
xlApp = new Excel.ApplicationClass();
xlWorkBook = xlApp.Workbooks.Open("C:\\Text Files\\test1.xlsx", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
range = xlWorkSheet.UsedRange;
string[,] excelArray = new string[range.Rows.Count, range.Columns.Count];
for (rCnt = 1; rCnt <= range.Rows.Count; rCnt++)
{
for (cCnt = 1; cCnt <= range.Columns.Count; cCnt++)
{
excelArray[rCnt - 1, cCnt - 1] = (string)(range.Cells[rCnt, cCnt] as Excel.Range).Value2.ToString();
//excelArray[rCnt - 1,cCnt - 1] = str;
//listBox1.Items.Add("location " + rCnt + "," + cCnt + " value " + excelArray[rCnt - 1, cCnt - 1] + excelArray[rCnt, cCnt - 1]);
this.dataGridView1.Rows.Add(excelArray[rCnt -1, cCnt - 1]);
//dataGridView1.DataSource = excelArray[rCnt - 1, cCnt - 1];
}
}
xlWorkBook.Close(true, null, null);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
}
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Unable to release the Object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
}
}
任何朝着正确方向的推动将不胜感激。