参考自:http://blog.csdn.net/polly_yang/article/details/8026149
一. txt中数据显示到datagridview中
private void button2_Click(object sender, EventArgs e)
{
//新建一个datatable用于保存读入数据
DataTable dt = new DataTable();
dt.Columns.Add("飞机编号", typeof(string));
dt.Columns.Add("到达时间", typeof(string));
dt.Columns.Add("剩余油量", typeof(string));
dt.Columns.Add("请求类型:起飞/降落", typeof(string));
//读入文件
StreamReader sr = new StreamReader(file_path, Encoding.Default);
while(!sr.EndOfStream)
{
string[] items = sr.ReadLine().Split(' ');
DataRow dr = dt.NewRow();
dr[0] = items[0];
dr[1] = items[1];
dr[2] = items[2];
dr[3] = items[3];
dt.Rows.Add(dr);
}
//将datatable绑定到datagridview上显示结果
dataGridView1.DataSource = dt;
}
二.datagridview保存到txt中
private void btnExportTxt_Click(object sender, EventArgs e)
{
string outFilePath = "";
SaveFileDialog SaveFileDialog1 = new SaveFileDialog();
SaveFileDialog1.Title = "导出TXT结果";
SaveFileDialog1.Filter = "导出TXT结果 (*.txt)|*.txt";
if (SaveFileDialog1.ShowDialog() == DialogResult.OK)
{
string saveFilename = SaveFileDialog1.FileName;
if (!string.IsNullOrEmpty(saveFilename))
{
outFilePath = SaveFileDialog1.FileName;
}
}
if (outFilePath == "")
{
MessageBox.Show("导出路径不存在!");
return;
}
if (dataGridView == null || dataGridView.Rows.Count == 0)
{
MessageBox.Show("导出行数不能为空!");
return;
}
FileStream fileStream = new FileStream(outFilePath, FileMode.OpenOrCreate);
StreamWriter streamWriter = new StreamWriter(fileStream, System.Text.Encoding.Unicode);
StringBuilder strBuilder = new StringBuilder();
try
{
//添加列名 \t为制表符Tab
for (int j = 0; j < dataGridView.Columns.Count; j++)
{
strBuilder.Append(dataGridView.Columns[j].Name.ToString() + "\t");
}
streamWriter.WriteLine(strBuilder.ToString());
//添加每行数据
for (int i = 0; i < dataGridView.Rows.Count; i++)
{
strBuilder = new StringBuilder();
for (int j = 0; j < dataGridView.Columns.Count; j++)
{
strBuilder.Append(dataGridView.Rows[i].Cells[j].Value.ToString() + "\t");
}
streamWriter.WriteLine(strBuilder.ToString());
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
streamWriter.Close();
fileStream.Close();
MessageBox.Show("导出完成!");
}
}
3.如果需要导出多个datagridview的数据,可以将
FileStream fileStream = new FileStream(filename, FileMode.OpenOrCreate);
改成:
FileStream fileStream = new FileStream(filename, FileMode.Append);
文件流以追加的形式写进去,这样后面DataGridView的数据也追加进去。