0
我使用ASP.net和C#将我的CSV文件上传到DataGrid中,它工作正常,但我试图使用Table而不是DataGrid,并且与我无关。因此,我有我的代码更改为查看数据到表 论文的代码,我使用DataGrid的上传csv文件到表格中而不是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;
}
}
}
有什么问题?你不这么说,谁能帮助你? –
你可以在这篇文章中找到解决问题的办法:http://stackoverflow.com/questions/19682996/datatable-to-html-table。 – ConnorsFan