DataGridView导入Excel时,出现了“未将对象引用设置到对象的实例”的解决办法
print?for (int i = 0; i < iRows - 1; i++)
{
for (int j = 1, k = 0; j < iCols; j++)
{
if (dgvStudent.Columns[j].Visible)
{
dimArray[i + 1, k] = dgvStudent.Rows[i].Cells[j].Value.ToString();
k++;
}
}
}
for (int i = 0; i < iRows - 1; i++)
{
for (int j = 1, k = 0; j < iCols; j++)
{
if (dgvStudent.Columns[j].Visible)
{
dimArray[i + 1, k] = dgvStudent.Rows[i].Cells[j].Value.ToString();
k++;
}
}
}[csharp] view plaincopyprint?//其中public System.Windows.Forms.DataGridView dgvStudent;,dimArray为Excel中的单元格,即
//其中public System.Windows.Forms.DataGridView dgvStudent;,dimArray为Excel中的单元格,即[csharp] view plaincopyprint?//ws.get_Range(ws.Cells[1, 1], ws.Cells[iRows, iCols]).Value2 = dimArray;
//ws.get_Range(ws.Cells[1, 1], ws.Cells[iRows, iCols]).Value2 = dimArray;[csharp] view plaincopyprint?//ws 为Microsoft.Office.Interop.Excel.Worksheet
//ws 为Microsoft.Office.Interop.Excel.Worksheet
这是从Datagridview导入Excel时的代码,但是出现了“未将对象引用设置到对象的实例”这个错误,我以为是不是我手动添加列时添加的不正确,所以我把函数 dgvStudent.Columns.Add(列名字符串变量, 列头名称字符串变量);改为了
[csharp]
DataGridViewTextBoxColumn column = new DataGridViewTextBoxColumn();
column.HeaderText = sh;
column.Name = quesId;
column.ReadOnly = false;
dgvStudent.Columns.Add(column);
DataGridViewTextBoxColumn column = new DataGridViewTextBoxColumn();
column.HeaderText = sh;
column.Name = quesId;
column.ReadOnly = false;
dgvStudent.Columns.Add(column);不用DataGridViewColumn column = new DataGridViewColumn();由于会出现CellType为空的错误。
但是还会有“未将对象引用设置到对象的实例”错误,因此不是手动添加列的错误。此时定位到Datagridview单元格与Excell的关系,
[csharp]
for (int i = 0; i < iRows - 1; i++)
{
for (int j = 1, k = 0; j < iCols; j++)
{
if (dgvStudent.Columns[j].Visible)
{
if (dgvStudent.Rows[i].Cells[j].ValueType == typeof(string))
{
dimArray[i + 1, k] = dgvStudent.Rows[i].Cells[j].Value.ToString();
k++;
}
else//很重要,因为DataGridView单元格有null的时候
{
if (dgvStudent[j, i].Value == null)
{
dgvStudent[j, i].Value = string.Empty;
 
补充:软件开发 , C# ,