C#从CSV数据创建图表

时间:2014-10-30 08:18:26

标签: c# csv charts

我尝试读取CSV数据并将其显示在Visual Studio的图表中。我收到一个SystemArgument.Exception,它告诉我他找不到名为“Date”的列。

我的代码如下:

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();
}

有什么问题?我希望有人可以帮助我... .Csv数据是: 两列 - 第一列第一行是Date               第二列第一行是Value 第一列中的行看起来是01.04.2010 - 第二列中的行看起来像234.567

1 个答案:

答案 0 :(得分:0)

我很确定Select * from test.csv无效。试试这段代码

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是csv表的名称,您应该用正确的值替换它!

请注意csv是否具有列名称连接字符串中的HDR应为YES

我给你的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();

sheetName是Table,看看我如何在sheetName之后添加$这是至关重要的。现在在tb你有excel数据!