导出DataGridView为CSV文本文件
本文关键字:文本 文件 CSV DataGridView 导出 | 更新日期: 2023-09-27 18:19:04
我编写了以下代码,但它不起作用(它将愚蠢的东西保存在我的CSV文件中)。会出什么问题呢?我的DataGridView有两列
var strValue = new StringBuilder();
foreach(DataGridViewRow row in dataGridView1.Rows)
{
strValue.AppendLine(row.Cells[0] + "," + row.Cells[1]);
}
string strFile = Properties.Settings.Default.AutoCompleteFile; //File Path
if (!string.IsNullOrEmpty(strValue.ToString()))
{
File.WriteAllText(strFile, strValue.ToString(), Encoding.UTF8);
}
这是我得到的结果在保存文件:
DataGridViewTextBoxCell {ColumnIndex=0, RowIndex=0},DataGridViewTextBoxCell {ColumnIndex=1, RowIndex=0}DataGridViewTextBoxCell {ColumnIndex=0, RowIndex=1},DataGridViewTextBoxCell {ColumnIndex=1, RowIndex=1}DataGridViewTextBoxCell {ColumnIndex=0, RowIndex=2},DataGridViewTextBoxCell {ColumnIndex=1, RowIndex=2}DataGridViewTextBoxCell {ColumnIndex=0, RowIndex=3},DataGridViewTextBoxCell {ColumnIndex=1, RowIndex=3}DataGridViewTextBoxCell {ColumnIndex=0, RowIndex=4},DataGridViewTextBoxCell {ColumnIndex=1, RowIndex=4}DataGridViewTextBoxCell {ColumnIndex=0, RowIndex=5},DataGridViewTextBoxCell {ColumnIndex=1, RowIndex=5}DataGridViewTextBoxCell {ColumnIndex=0, RowIndex=6},DataGridViewTextBoxCell {ColumnIndex=1, RowIndex=6}DataGridViewTextBoxCell {ColumnIndex=0, RowIndex=7},DataGridViewTextBoxCell {ColumnIndex=1, RowIndex=7}DataGridViewTextBoxCell {ColumnIndex=0, RowIndex=8},DataGridViewTextBoxCell {ColumnIndex=1, RowIndex=8}DataGridViewTextBoxCell {ColumnIndex=0, RowIndex=9},DataGridViewTextBoxCell {ColumnIndex=1, RowIndex=9}DataGridViewTextBoxCell {ColumnIndex=0, RowIndex=10},DataGridViewTextBoxCell {ColumnIndex=1, RowIndex=10}
当你调用这个时:
strValue.AppendLine(row.Cells[0] + "," + row.Cells[1]);
。Net正在对每个单元格做一个"ToString",而不是它们的值。这是row.Cells[x]
的类型:http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewcell.aspx
使用Value属性可能会解决你的问题:
strValue.AppendLine(row.Cells[0].Value + "," + row.Cells[1].Value);