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;
}
dimArray[i + 1, k] = dgvStudent[j, i].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)
{
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;
}
dimArray[i + 1, k] = dgvStudent[j, i].Value.ToString();
k++;
}
}
}
}此時,我了解到原來是DataGridView單元格值為null,無法轉化為string。