将csv文件上传到表而不是DataGrid

时间:2016-04-30 21:47:51

标签: c# asp.net

我使用ASP.net和C#将我的CSV文件上传到DataGrid并且它有效,但我尝试使用Table而不是DataGrid并且无法使用。所以我必须在我的代码中更改以查看表中的数据 这两行代码我使用了dataGrid

 DataGrid.DataSource = GetDataTableFromCSVFile(currentPath);
 DataGrid.DataBind();

以及所有代码

 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Web;
 using System.Web.UI;
 using System.Web.UI.WebControls;
 using System.Data;
 using System.IO;
 using Microsoft.VisualBasic.FileIO;

 namespace Csvfile
 {
 public partial class WebForm1 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }

    protected void btCSVUpload_Click(object sender, EventArgs e)
    {
        if (FileUploadControl.HasFile)
        {
            try
            {
                string currentPath = Server.MapPath("~/") +
                              Path.GetFileName(FileUploadControl.FileName);
                FileUploadControl.SaveAs(currentPath);

                DataGrid.DataSource = GetDataTableFromCSVFile(currentPath);
                DataGrid.DataBind();
                lbStatus.Text = "CSV Upload status: File uploaded!";

                File.Delete(currentPath);
            }
            catch (Exception ex)
            {
                lbStatus.Text = @"CSV Upload status: The file could not be  uploaded. 
                The following error has occured: " + ex.Message;
            }
        }
        else
        {
            lbStatus.Text = "CSV Upload status: File not found.";
        }
    }

    private static DataTable GetDataTableFromCSVFile(string csvfilePath)
    {
        DataTable csvData = new DataTable();
        using (TextFieldParser csvReader = new TextFieldParser(csvfilePath))
        {
            csvReader.SetDelimiters(new string[] { "," });
            csvReader.HasFieldsEnclosedInQuotes = true;

            //Read columns from CSV file, remove this line if columns not exits  
            string[] colFields = csvReader.ReadFields();

            foreach (string column in colFields)
            {
                DataColumn datecolumn = new DataColumn(column);
                datecolumn.AllowDBNull = true;
                csvData.Columns.Add(datecolumn);
            }

            while (!csvReader.EndOfData)
            {
                string[] fieldData = csvReader.ReadFields();
                //Making empty value as null
                for (int i = 0; i < fieldData.Length; i++)
                {
                    if (fieldData[i] == "")
                    {
                        fieldData[i] = null;
                    }
                }
                csvData.Rows.Add(fieldData);
            }
        }
        return csvData;
    }
}

}

1 个答案:

答案 0 :(得分:0)

ASP.NET在构建响应时将DataGrid转换为HTML表。如果从浏览器查看源代码,则可以看到网格呈现为HTML表格。