1

我有这个具有以下结构的 MS Access 表:

在此处输入图像描述

我将数据提取到没有文本限定符的制表符分隔的文本文件中:

在此处输入图像描述

我找到了这篇文章,但它不适用于制表符分隔的文件。我不知道如何将这些数据显示到 DataGridView 中,包括标题。你能帮我么?

提前致谢。

4

1 回答 1

0
DataGridView1.DataSource = CsvFileToDatatable(@"c:\a.csv",true);

public DataTable CsvFileToDatatable(string path, bool IsFirstRowHeader)//here Path is root of file and IsFirstRowHeader is header is there or not
        {
            string header = "No";
            string sql = string.Empty;
            DataTable dataTable = null;
            string pathOnly = string.Empty;
            string fileName = string.Empty;

            try
            {

                pathOnly = Path.GetDirectoryName(path);
                fileName = Path.GetFileName(path);

                sql = @"SELECT * FROM [" + fileName + "]";

                if (IsFirstRowHeader)
                {
                    header = "Yes";
                }

                using (OleDbConnection connection = new OleDbConnection(
                        @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathOnly +
                        ";Extended Properties=\"Text;HDR=" + header + "\""))
                {
                    using (OleDbCommand command = new OleDbCommand(sql, connection))
                    {
                        using (OleDbDataAdapter adapter = new OleDbDataAdapter(command))
                        {
                            dataTable = new DataTable();
                            dataTable.Locale = CultureInfo.CurrentCulture;
                            adapter.Fill(dataTable);

                        }
                    }
                }
            }
            finally
            {

            }

            return dataTable;

        }
于 2012-05-08T04:36:50.187 回答