将DataGridView导出到带有标题的文本文件

时间:2016-06-08 16:14:11

标签: c# winforms datagridview

我想将Date.new(2016,1,1).cweek % 53 + 1 # week starts with Monday 导出到文本文件中。我写这段代码。它工作正常,但我也想将列标题写入文本文件。

DataGridView

2 个答案:

答案 0 :(得分:2)

我会使用内置功能(GetClipboardContent()方法)

SaveFileDialog dialog = new SaveFileDialog();
dialog.Filter = "Text File|*.txt";
var result = dialog.ShowDialog();
if (result != DialogResult.OK)
    return;

// setup for export
dgvSum.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText;
dgvSum.SelectAll();
// hiding row headers to avoid extra \t in exported text
var rowHeaders = dgvSum.RowHeadersVisible;
dgvSum.RowHeadersVisible = false;

// ! creating text from grid values
string content = dgvSum.GetClipboardContent().GetText();

// restoring grid state
dgvSum.ClearSelection();
dgvSum.RowHeadersVisible = rowHeaders;

System.IO.File.WriteAllText(dialog.FileName, content);
MessageBox.Show(@"Text file was created.");

答案 1 :(得分:1)

所以你需要在第一个master循环之前使用这一行:

for