问题描述
我正在开发一个应用程序,它将我的 DataGridView 称为scannerDataGridView 导出到一个 csv 文件.
I'm working on a application which will export my DataGridView called scannerDataGridView to a csv file.
找到了一些示例代码来执行此操作,但无法使其正常工作.顺便说一句,我的数据网格不是数据绑定到源.
Found some example code to do this, but can't get it working. Btw my datagrid isn't databound to a source.
当我尝试使用 Streamwriter 仅写入列标题时一切顺利,但是当我尝试导出包括数据在内的整个数据网格时,我得到了一个例外.
When i try to use the Streamwriter to only write the column headers everything goes well, but when i try to export the whole datagrid including data i get an exeption trhown.
System.NullReferenceException:未将对象引用设置为实例的一个对象.在 Scanmonitor.Form1.button1_Click(对象发送者,事件参数 e)
这是我的代码,以下行给出了错误:
Here is my Code, error is given on the following line:
dataFromGrid = dataFromGrid + ',' + dataRowObject.Cells[i].Value.ToString();
//csvFileWriter = StreamWriter
//scannerDataGridView = DataGridView
private void button1_Click(object sender, EventArgs e)
{
string CsvFpath = @"C:scannerCSV-EXPORT.csv";
try
{
System.IO.StreamWriter csvFileWriter = new StreamWriter(CsvFpath, false);
string columnHeaderText = "";
int countColumn = scannerDataGridView.ColumnCount - 1;
if (countColumn >= 0)
{
columnHeaderText = scannerDataGridView.Columns[0].HeaderText;
}
for (int i = 1; i <= countColumn; i++)
{
columnHeaderText = columnHeaderText + ',' + scannerDataGridView.Columns[i].HeaderText;
}
csvFileWriter.WriteLine(columnHeaderText);
foreach (DataGridViewRow dataRowObject in scannerDataGridView.Rows)
{
if (!dataRowObject.IsNewRow)
{
string dataFromGrid = "";
dataFromGrid = dataRowObject.Cells[0].Value.ToString();
for (int i = 1; i <= countColumn; i++)
{
dataFromGrid = dataFromGrid + ',' + dataRowObject.Cells[i].Value.ToString();
csvFileWriter.WriteLine(dataFromGrid);
}
}
}
csvFileWriter.Flush();
csvFileWriter.Close();
}
catch (Exception exceptionObject)
{
MessageBox.Show(exceptionObject.ToString());
}
推荐答案
发现问题,编码没问题,但我有一个空单元格导致了问题.
Found the problem, the coding was fine but i had an empty cell that gave the problem.
这篇关于将数据网格视图导出到 csv 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!