简体   繁体   English

C#从CSV数据创建图表

[英]C# creating Chart from CSV data

I tried to read a CSV Data and display it in a Chart in Visual Studio. 我试图读取CSV数据并将其显示在Visual Studio的图表中。 I get a SystemArgument.Exception and it tolds me that he couldn't find the Column with the name "Date". 我得到一个SystemArgument.Exception,它告诉我他找不到名称为“ Date”的列。

My Code is the following: 我的代码如下:

private void button1_Click_1(object sender, EventArgs e)
{

string file = "test.csv";
string dir = "C:\\Main";

string ConStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
            dir + ";Extended Properties=\"Text;HDR=No;FMT=Delimited\"";
OleDbConnection myConnection = new OleDbConnection(ConStr);

string mySelectQuery = "Select * from " + file;
OleDbCommand myCommand = new OleDbCommand(mySelectQuery, myConnection);

myCommand.Connection.Open();
OleDbDataReader myReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);

chart1.Series["Test"].Points.DataBindXY(myReader, "Date",myReader,"Value");
chart1.Series["Test"].ChartType = SeriesChartType.Line;

myReader.Close();
myConnection.Close();
}

What is wrong? 怎么了? I hope someone can help me... the .Csv data is: Two columns - First column first row is Date Second Column first row is Value The Rows in the first column look 01.04.2010 - the Rows in the second column look like 234.567 希望有人能帮助我... .csv数据是:两列-第一列第一行是日期第二列第一行是值第一列中的行看起来是01.04.2010-第二列中的行看起来像234.567

I'm pretty sure that Select * from test.csv will not work. 我非常确定, Select * from test.csv中的Select * from test.csv将不起作用。 Try this code 试试这个代码

string file = @"C:\Main\test.csv";

string connString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
            file + ";Extended Properties=\"Text;HDR=No;FMT=Delimited\"";

string query = @"select * from sheetName$";

sheetName is the name of the csv sheet, you should replace it with the right value ! sheetName是csv工作表的名称,您应该将其替换为正确的值!

Be aware if the csv has column names HDR should be YES in connection string 请注意,csv是否具有列名HDR在连接字符串中应为YES

I'm giving you working example with xslx file ! 我给你xslx文件的工作示例!

       string file = @"C:\Projects\EverydayProject\test.xlsx";

       string connString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
                    file + ";Extended Properties='Excel 12.0 Xml;HDR=YES;'";

        OleDbConnection conn = new OleDbConnection(connString);
        conn.Open();
        string query = @"select * from [Table$]";

        DataTable tb = new DataTable();
        using(OleDbDataAdapter ad = new OleDbDataAdapter(query, conn))
        {
            ad.Fill(tb);
        }

        conn.Close();

The sheetName is Table, look how I add $ after the sheetName this is critical. sheetName是Table,看看我如何在sheetName之后添加$ ,这很关键。 Now in the tb you have the excel data ! 现在,在tb中,您拥有了excel数据!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM