获取错误对象引用未设置为对象的实例。如果我删除DataGridViewComboBoxColumn然后它正在导出正常但我需要在excel中导出带有选定值的下拉列表。我刚刚在datagrid视图中添加了一些数据,如下所示:
dataGridView1.ColumnCount = 3;
dataGridView1.Columns[0].Name = "Product ID";
dataGridView1.Columns[1].Name = "Product Name";
dataGridView1.Columns[2].Name = "Product Price";
string[] row = new string[] { "1", "Product 1", "1000" };
dataGridView1.Rows.Add(row);
row = new string[] { "2", "Product 2", "2000" };
dataGridView1.Rows.Add(row);
row = new string[] { "3", "Product 3", "3000" };
dataGridView1.Rows.Add(row);
row = new string[] { "4", "Product 4", "4000" };
dataGridView1.Rows.Add(row);
DataGridViewComboBoxColumn cmb = new DataGridViewComboBoxColumn();
cmb.HeaderText = "Select Data";
cmb.Name = "cmb";
cmb.MaxDropDownItems = 4;
cmb.Items.Add("True");
cmb.Items.Add("False");
dataGridView1.Columns.Add(cmb);
//导出到Excel
worksheet = workbook.ActiveSheet;
worksheet.Name = "test";
int cellRowIndex = 1;
int cellColumnIndex = 1;
for (int i = 1; i < dataGridView1.Columns.Count + 1; i++)
{
worksheet.Cells[1, i] = dataGridView1.Columns[i - 1].HeaderText;
}
MessageBox.Show(dataGridView1.ColumnCount.ToString());
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
for (int j = 0; j < dataGridView1.Columns.Count; j++)
{
worksheet.Cells[i + 2, j + 1] = dataGridView1.Rows[i].Cells[j].Value.ToString();
cellColumnIndex++;
}
cellColumnIndex = 1;
cellRowIndex++;
}
//Getting the location and file name of the excel to save from user.
SaveFileDialog saveDialog = new SaveFileDialog();
//saveDialog.Filter = "Excel files (*.xlsx)|*.xlsx|All files (*.*)|*.*";
saveDialog.Filter = "Excel files (All files (*.*)|*.*";
saveDialog.FilterIndex = 2;
if (saveDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
workbook.SaveAs(saveDialog.FileName);
MessageBox.Show("Export Successful");
}
答案 0 :(得分:0)
尝试此操作从组合框中检索所选值
dataGridView1.Rows[0].Cells[i].FormattedValue.ToString();
您可以使用相同的方法从单元格值而不是Rows [0]中检索.Cells [i] .value
在你的情况下
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
for (int j = 0; j < dataGridView1.Columns.Count; j++)
{
worksheet.Cells[i + 2, j + 1] = dataGridView1.Rows[i].Cells[j].FormattedValue.ToString();
cellColumnIndex++;
}
cellColumnIndex = 1;
cellRowIndex++;
}