从CSV读取数据到屏幕输出

时间:2015-05-08 17:19:10

标签: c# c++ c windows csv

这可能是不允许的,但无论如何我都会问。

我正在尝试开发类似于YALV的产品,但是要开发自定义日志。

我有一个CSV文件,我想读入并在屏幕上显示在一个表格中,可以滚动,过滤,着色等,类似于YALV。

我有用于读取和解密CSV并以整齐格式输出到另一个文件的代码。我想调整它以使其进入屏幕。

我有C#和C的经验,但只有控制台相关。有人可以引导我指向正确的方向,至少在窗口中以与YALV类似的格式读取文件吗?我的可能步骤是什么?我不确定从哪里开始......

由于

1 个答案:

答案 0 :(得分:1)

下面的代码显示DataGridView

中的结果
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Data.OleDb;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        const string FILENAME = @"c:\temp\test.csv";
        private void button1_Click(object sender, EventArgs e)
        {
            CSVReader csvReader = new CSVReader();
            DataSet ds = csvReader.ReadCSVFile(FILENAME, true);
            dataGridView1.DataSource = ds.Tables["Table1"];
        }
    }
    public class CSVReader
    {

        public DataSet ReadCSVFile(string fullPath, bool headerRow)
        {

            string path = fullPath.Substring(0, fullPath.LastIndexOf("\\") + 1);
            string filename = fullPath.Substring(fullPath.LastIndexOf("\\") + 1);
            DataSet ds = new DataSet();

            try
            {
                if (File.Exists(fullPath))
                {
                    string ConStr = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0}" + ";Extended Properties=\"Text;HDR={1};FMT=Delimited\\\"", path, headerRow ? "Yes" : "No");
                    string SQL = string.Format("SELECT * FROM {0}", filename);
                    OleDbDataAdapter adapter = new OleDbDataAdapter(SQL, ConStr);
                    adapter.Fill(ds, "TextFile");
                    ds.Tables[0].TableName = "Table1";
                }
                foreach (DataColumn col in ds.Tables["Table1"].Columns)
                {
                    col.ColumnName = col.ColumnName.Replace(" ", "_");
                }
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            return ds;
        }
    }
}

​
相关问题