我正在开发一个项目,我必须导入一个CSV文件,并在DataGridView中显示结果。我正在努力将我的数据字段显示到我的datagridview,我希望能够一次添加每一行,以便正确地解析它们。到目前为止,这是我的代码。
csv.MissingFieldAction = MissingFieldAction.ReplaceByNull;
int fieldCount = csv.FieldCount;
string[] headers = csv.GetFieldHeaders();
fieldCount = fieldCount - 1;
//TO DO: Reading Header Information
for (int i = 0; i <= fieldCount; i++)
{
DataGridViewTextBoxColumn headerRow = new DataGridViewTextBoxColumn();
headerRow.Name = headers[i];
headerRow.HeaderText = headers[i];
headerRow.Width = 100;
dgvComplianceImport.Columns.Add(headerRow);
}
while (csv.ReadNextRecord())
{
//for (int i = 0; i < fieldCount; i++)
// string.Format("{0} = {1};",
// headers[i],
// csv[i] == null ? "MISSING" : csv[i]);
//TO DO: for loop to add each data field row
DataGridViewRow dgvr = new DataGridViewRow();
for (int fieldCount = 0; fieldCount <= csv.FieldCount; fieldCount++)
{
string field = csv[fieldCount];
}
dgvr.Cells.Add(new DataGridViewCell());
dgvComplianceImport.Rows.Add(dgvr);
}
dgvComplianceImport.DataSource = csv;
}
答案 0 :(得分:1)
CSV文件是一个普通的文本文件,只逗号分隔。
基本上你要做的是打开文本文件并读取每一行并用逗号分隔(“,”)
使用这些链接。他们应该帮忙。 http://www.codeproject.com/Articles/16951/Populating-data-from-a-CSV-file-to-a-DataGridView
如果您仍需要一些帮助来编写代码,请告诉我。
答案 1 :(得分:1)
这就是我通常做的事情:
LINQToCSV
(请参阅here和here)阅读CSV文件。它已经给了我IEnumerable<T>
T
是我的班级。如何阅读CSV文件的示例
我们假设CSV文件包含列Name, Last Name, Age
然后定义以下类:
class Person {
[CsvColumn(FieldIndex = 0, CanBeNull = false, Name = "Name")]
public string Name { get; set; }
[CsvColumn(FieldIndex = 1, CanBeNull = true, Name = "Last Name")]
public string Last Name { get; set; }
[CsvColumn(FieldIndex = 2, CanBeNull = true, Name = "Age")]
public int Age { get; set; }
}
获得后,您可以从以下CSV文件中读取Person
列表:
public IEnumerable<Person> ReadFromCsv(string csvFile) {
//Here you set some properties. Check the documentation.
var csvFileDescription = new CsvFileDescription
{
FirstLineHasColumnNames = true,
SeparatorChar = ',' //Specify the separator character.
};
var csvContext = new CsvContext();
return csvContext.Read<Person>(csvFile, csvFileDescription);
}
答案 2 :(得分:0)
这是我使用的课程:
调用lCsv.ReadCsv(&#34;您的文件路径&#34;),该方法返回从.csv文件创建的数据表。
文件中的分隔符是&#34 ;;&#34;,.csv文件的第一行是标题名称。如果你要改变什么,请查看lCsv.ReadCsv方法
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Data;
namespace ReadWriteCsv
{
/// <summary>
/// Class to store one CSV row
/// </summary>
public class CsvRow : List<string>
{
public string LineText { get; set; }
}
/// <summary>
/// Class to read data from a CSV file
/// </summary>
public class CsvFileReader : StreamReader
{
public CsvFileReader(Stream stream)
: base(stream)
{
}
public CsvFileReader(string filename)
: base(filename)
{
}
/// <summary>
/// Reads a row of data from a CSV file
/// </summary>
/// <param name="row"></param>
/// <returns></returns>
public bool ReadRow(CsvRow row)
{
row.LineText = ReadLine();
if (String.IsNullOrEmpty(row.LineText))
return false;
int pos = 0;
int rows = 0;
while (pos < row.LineText.Length)
{
string value;
// Special handling for quoted field
if (row.LineText[pos] == '"')
{
// Skip initial quote
pos++;
// Parse quoted value
int start = pos;
while (pos < row.LineText.Length)
{
// Test for quote character
if (row.LineText[pos] == '"')
{
// Found one
pos++;
// If two quotes together, keep one
// Otherwise, indicates end of value
if (pos >= row.LineText.Length || row.LineText[pos] != '"')
{
pos--;
break;
}
}
pos++;
}
value = row.LineText.Substring(start, pos - start);
value = value.Replace("\"\"", "\"");
}
else
{
// Parse unquoted value
int start = pos;
while (pos < row.LineText.Length /*&& row.LineText[pos] != ','*/)
pos++;
value = row.LineText.Substring(start, pos - start);
}
// Add field to list
if (rows < row.Count)
row[rows] = value;
else
row.Add(value);
rows++;
// Eat up to and including next comma
while (pos < row.LineText.Length /*&& row.LineText[pos] != ','*/)
pos++;
if (pos < row.LineText.Length)
pos++;
}
// Delete any unused items
while (row.Count > rows)
row.RemoveAt(rows);
// Return true if any columns read
return (row.Count > 0);
}
}
public class lCsv
{
public static DataTable ReadCsv(string sPath)
{
DataTable dtIssues = new DataTable();
int iRowCount = 0;
int iColumnCount = 0;
// Read sample data from CSV file
using (CsvFileReader reader = new CsvFileReader(sPath))
{
CsvRow row = new CsvRow();
while (reader.ReadRow(row))
{
foreach (string fullrow in row)
{
if (iRowCount == 0)
{
foreach (string sName in fullrow.Split(';'))
{
dtIssues.Columns.Add(sName);
iColumnCount++;
}
iRowCount++;
}
else
{
DataRow drIssue = dtIssues.NewRow();
int iAddCount = 0;
foreach (string sName in fullrow.Split(';'))
{
if (iAddCount < iColumnCount)
{
drIssue[iAddCount] = sName;
iAddCount++;
}
}
dtIssues.Rows.Add(drIssue);
}
}
}
}
return dtIssues;
}
}
}
答案 3 :(得分:0)
为什么重新发明轮子? FileHelpers
是你的朋友。
此处给出了如何将CSV导入DataTable的示例: http://www.filehelpers.net/docs/html/M_FileHelpers_CsvEngine_CsvToDataTable_2.htm
相关类(CsvEngine
)下的静态方法签名就像这样简单:
public static DataTable CsvToDataTable(
string filename,
string classname,
char delimiter
)
甜蜜,对吧?
答案 4 :(得分:0)
简短而有效,希望有所帮助
DataGridView my_dgvCSV = new DataGridView();
DataTable my_dataTable = new DataTable();
private void Form1_Load(object sender, EventArgs e)
{
this.Size = new Size(750, 450);
my_dgvCSV.Size = new Size(600, 400);
my_dgvCSV.Location = new Point(5, 5);
string[] raw_txt = File.ReadAllLines(@"D:\urPath\xyz.csv");
string[] data_col = null;
int x = 0;
foreach (string txt_line in raw_txt)
{
data_col = txt_line.Split(';');
// My .csv wanted (';') if it looks weird/wrong use (',')
if (x == 0)
{//header
for (int i = 0; i <= data_col.Count() -1; i++)
{
my_dataTable.Columns.Add(data_col[i]);
}
x++;
}
else
{//data
my_dataTable.Rows.Add(data_col);
}
}
my_dgvCSV.DataSource = my_dataTable;
this.Controls.Add(my_dgvCSV);
}