我有数据表,我在datagridview中使用代码显示这些值:
dataGridView1.ColumnCount = TableWithOnlyFixedColumns.Columns.Count;
dataGridView1.RowCount = TableWithOnlyFixedColumns.Rows.Count;
for (int i = 0; i < dataGridView1.RowCount; i++)
{
for (int j = 0; j < dataGridView1.ColumnCount; j++)
{
dataGridView1[j, i].Value = TableWithOnlyFixedColumns.Rows[i][j].ToString();
}
}
TableExtractedFromFile.Clear();
TableWithOnlyFixedColumns.Clear();
现在我想将记录保存在csv文件的数据表中。我该怎么做?
答案 0 :(得分:1)
你可以这样做:
// we'll use these to check for rows with nulls
var columns = yourTable.Columns
.Cast<DataColumn>();
// say the column you want to sort by is called "Date"
var rows = yourTable.Select("", "Date ASC"); // or "Date DESC"
using (var writer = new StreamWriter(yourPath)) {
for (int i = 0; i < rows.Length; i++) {
DataRow row = rows[i];
// check for any null cells
if (columns.Any(column => row.IsNull(column)))
continue;
string[] textCells = row.ItemArray
.Select(cell => cell.ToString()) // may need to pick a text qualifier here
.ToArray();
// check for non-null but EMPTY cells
if (textCells.Any(text => string.IsNullOrEmpty(text)))
continue;
writer.WriteLine(string.Join(",", textCells));
}
}