You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将DataGridView指定列导出为分号分隔的.inp格式文本文件

C# WinForm DataGridView指定列导出为分号分隔文本文件实现方案
  • 提前确认你需要导出的3列的列名或者列索引,示例中我们假设需要导出的3列索引为0、2、4,你可以替换成你实际需要的列索引或者列名
  • 导出时默认跳过DataGridView的空白待输入新行,如果你需要导出表头可以自行调整代码逻辑

完整实现代码

// 引入必要命名空间
using System.IO;
using System.Text;
using System.Windows.Forms;
using System.Collections.Generic;

// 导出核心方法
private void ExportSpecifiedColumnsToTxt(DataGridView dgv, string savePath)
{
    // 按你的需求修改这里的列索引,对应要导出的3列
    int[] exportColumnIndexes = new int[] { 0, 2, 4 };
    
    StringBuilder sb = new StringBuilder();
    
    // 遍历所有行
    foreach (DataGridViewRow row in dgv.Rows)
    {
        // 跳过空白待输入行,不需要可以删除这行
        if (row.IsNewRow) continue;
        
        List<string> rowValues = new List<string>();
        // 仅提取指定列的值
        foreach (int colIndex in exportColumnIndexes)
        {
            // 处理空值避免报错
            string cellValue = row.Cells[colIndex].Value?.ToString() ?? string.Empty;
            rowValues.Add(cellValue);
        }
        // 用英文分号拼接为一行
        sb.AppendLine(string.Join(";", rowValues));
    }
    
    // 写入文件,编码按需调整,中文系统可以换成Encoding.GetEncoding("GB2312")
    File.WriteAllText(savePath, sb.ToString(), Encoding.UTF8);
    MessageBox.Show("导出完成");
}

调用示例

可以配合SaveFileDialog让用户选择保存路径,示例代码如下:

private void btnExport_Click(object sender, EventArgs e)
{
    SaveFileDialog sfd = new SaveFileDialog();
    sfd.Filter = "文本文件(*.txt)|*.txt";
    sfd.FileName = "导出数据.txt";
    if (sfd.ShowDialog() == DialogResult.OK)
    {
        // 把dataGridView1替换成你实际的控件名
        ExportSpecifiedColumnsToTxt(dataGridView1, sfd.FileName);
    }
}

其他说明

  • 如果要通过列名指定导出列,把exportColumnIndexes改成string[] exportColumnNames = new string[] {"列名1","列名2","列名3"},取值代码换成row.Cells[colName].Value即可
  • 如果需要导出表头,在遍历行之前先拼接一遍表头行的指定列名称即可
  • 如果单元格值本身包含英文分号,可以自行加转义逻辑,比如给每个值包裹双引号

内容的提问来源于stack exchange,提问作者BPr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 06:54:07