如何将分隔符从逗号更改为分号?

时间:2017-03-29 09:35:22

标签: c# csv

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Data.OleDb;
using System.Reflection;
using CsvHelper.Configuration;

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

        public DataTable ReadCsv(string filename)
        {
            DataTable dt = new DataTable("Data");
            using (OleDbConnection cn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"" +
                Path.GetDirectoryName(filename) + "\";Extended Properties='text;HDR=yes;FMT=Delimited(;)';"))
            {
                using (OleDbCommand cmd = new OleDbCommand(string.Format("select *from [{0}]", new FileInfo(filename).Name), cn))
                {
                    cn.Open();
                    using (OleDbDataAdapter adapter = new OleDbDataAdapter(cmd))
                    {
                        adapter.Fill(dt);
                    }
                }
            }

            return dt;
        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            try
            {
                using (OpenFileDialog ofd = new OpenFileDialog() { Filter = "CSV| *.csv", ValidateNames = true, Multiselect = true })
                {
                    if (ofd.ShowDialog() == DialogResult.OK)
                        dataGridView.DataSource = ReadCsv(ofd.FileName);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}

事实证明,我尝试阅读的csv文件使用分号(;)作为分隔符,而不是通常的逗号(,)。

我试图更改分隔符,但由于某种原因无法更改。

我希望得到任何帮助!

1 个答案:

答案 0 :(得分:2)

我想你只需要改变它:

using (OleDbConnection cn = new 
          OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"" +
               Path.GetDirectoryName(filename) + 
               "\";Extended Properties='text;HDR=yes;FMT=Delimited(;)';"))

到此:

using (OleDbConnection cn = new 
          OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"" +
               Path.GetDirectoryName(filename) + 
               "\";Extended Properties='text;HDR=yes;FMT=Delimited(,)',"))

将OleDb连接字符串中的FMT=Delimited(;)';更改为FMT=Delimited(,)',

更新抱歉,我误解了您原来的问题 - 您已经将分隔符更改为;中的OleDbConnection - 错过了之一。

老实说:我不知道你应该做什么以及你应该做什么(除了你已经做过的事情)来让这个OleDbConnection和命令正常工作......

就个人而言,我会使用优秀的(和免费!)CsvHelper组件来读取我可能需要导入的任何CSV文件 - 而不是OleDb的东西.....与CsvHelper,它非常很容易定义分隔符(以及导入的更多属性),它就像一个魅力,从任何List<YourEntity>文件返回.csv,随时可以按照您想要的方式使用

相关问题