在C#中将CSV文件导出到DataGridview

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在C#中将CSV文件导出到DataGridview相关的知识,希望对你有一定的参考价值。

我正在使用以下代码将CSV文件内容导出到C#中的DataGridView。我的Windows应用程序已成功运行,但甚至不显示Datagridview或输出中的任何内容。

我不知道确切的问题在哪里。

我的目标是在datagridview中显示.csv文件的内容。我已将.csv文件存储在我的C驱动器中,如路径中所指定。

Using System.data.Odbc;

namespace finaltry
{
    public partial class Form1 : Form
    {

        private void Form1_Load(object sender, System.EventArgs e)
        {


            string  ConnectionString = @"Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq=c:;Extensions=asc,csv,tab,txt";

            OdbcConnection conn = new OdbcConnection(ConnectionString);
            try
            {
                conn.Open();
                OdbcDataAdapter da = new OdbcDataAdapter("Select * FROM SharedIncidents.csv", conn);
                DataSet ds = new DataSet();
                da.Fill(ds, "SharedIncidents");
                dataGridView1.DataSource = ds.DefaultViewManager;
                conn.Close(); 

            }
            catch (System.Exception)
            {

                MessageBox.Show("error is" );



            }

        }
    }
}

我的应用程序运行成功,但没有在datagridview中显示任何内容。谁能告诉我问题出在哪里?

答案

请尝试使用此示例代码,这很好,我可以将csv内容绑定到Gridview控件。

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CSVSample.aspx.cs" Inherits="CSVSample" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:GridView runat="server" ID="gv_csvupload">
    </asp:GridView>
    </div>
    </form>
</body>
</html>

代码隐藏

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.OleDb;
using System.Data;
public partial class CSVSample : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

        string ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + "E:\FolderName\" + ";Extended Properties='text;HDR=Yes'";
        //sample.csv is the csv which i used for my demo
        string CommandText = "select * from Sample.csv";
        OleDbConnection conn = new OleDbConnection(ConnectionString);
        conn.Open();
        OleDbDataAdapter da=new OleDbDataAdapter(CommandText,conn);
        DataSet Sample=new DataSet();
        da.Fill(Sample);
        conn.Close();
        conn.Dispose();
        gv_csvupload.DataSource = Sample;
        gv_csvupload.DataBind();                
    }
}
另一答案

正如@Ramakrishnan在他的样本中提到的......我认为你唯一缺少的就是

dataGridView1.DataBind();

子句......基本上将数据推入网格中进行显示。

以上是关于在C#中将CSV文件导出到DataGridview的主要内容,如果未能解决你的问题,请参考以下文章

将datagridview导出到csv文件

c#中将datagridview中数据导出到excel中,点击保存可以保存,点击取消就出

在c#中将数据导出到Excel时出错(获胜表单)

在 Julia 中将数组导出到 CSV 文件

在android中将房间数据库导出到csv文件

如何在 VB.NET 中将 DataGridView 导出为 Excel 格式