C# C语言中的DataGridView导出器#

C# C语言中的DataGridView导出器#,c#,exception,datagridview,export,streamwriter,C#,Exception,Datagridview,Export,Streamwriter,我在将数据从DataGridView导出到.txt文件时遇到问题 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; namespace TSQ { class TxtExporter : IExporter { public void Export(Da

我在将数据从DataGridView导出到.txt文件时遇到问题

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace TSQ
{
    class TxtExporter : IExporter
    {
        public void Export(DataGridView dataGrid, Output output)
        {
            if (output == null)
                return;

            string filePath = output.TemplatePath;

            try
            {
                using (StreamWriter sw = new StreamWriter(filePath))
                {
                    for (int row = 0; row < dataGrid.Rows.Count; row++)
                    {
                        for (int col = 0; col < dataGrid.Columns.Count; col++)
                        {
                            sw.Write(dataGrid[col, row].Value.ToString());
                            sw.Write('\t');
                        }
                        sw.WriteLine();
                        //sw.Flush(); <- also doesn`t work if uncommented
                    }
                }
            }
            catch (Exception)
            {
                //MessageBox.Show(exc.Message);
                throw;
            }
        }
    }
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
使用System.Windows.Forms;
使用System.IO;
名称空间TSQ
{
类TxtExporter:IExporter
{
公共void导出(DataGridView dataGrid,输出)
{
if(输出==null)
返回;
字符串filePath=output.TemplatePath;
尝试
{
使用(StreamWriter sw=新StreamWriter(文件路径))
{
for(int row=0;row//sw.Flush();如果它不必是.txt,请尝试导出到Excel


Ref

您是否尝试过在DataGridView中循环并将内容保存到StringBuilder(),然后使用StreamWriter将该字符串写入您的文本文件?可能与我在剪贴板中尝试的字符串重复,但其工作速度会变慢,还会导致内存不足异常:(目前我可以选择导出到Excel中-我只是使用另一个类来处理这个“ExcelExporter”。但是这需要很多时间,而且对于大数据(>100K),它也会导致OutOfMemoryException