![](/img/trans.png)
[英]Is there a way to populate an ObservableCollection in Xamarin.Forms by reading a csv file?
[英]Reading from a CSV file to a label in Xamarin.Forms
我在这里阅读了一个教程,但我仍然无法弄清楚如何从 CSV 中成功读取一行以显示在 label 上。 按照教程的建议,我创建了一个 CsvFileReader class,但我不知道如何使用它从 CSV 中读取一行并将其粘贴到 label 上。
Label label = new Label
{
// Text = the 5th column of the 1st row of 'my_file.csv'
VerticalTextAlignment = TextAlignment.Center,
HorizontalTextAlignment = TextAlignment.Center,
FontSize = 25,
TextColor = Color.Black,
HeightRequest = 80
};
您可以使用CsvHelper
读取 csv 数据。 从 NuGet Package 安装CsvHelper
。
创建一个.csv文件并放入Xamarin.Forms项目中。
.csv文件数据:我将数据写入excel并另存为.csv文件。 Excel 数据表中没有逗号。
ID,Name,Age
1,A,11
2,B,12
3,C,13
4,D,14
5,E,15
将 Build Action 设置为Embedded resource
。
为 .csv 文件创建结构。
public class test
{
public string ID { get; set; }
public string Name { get; set; }
public string Age { get; set; }
}
从 .csv 文件中读取。
private void Button_Clicked(object sender, EventArgs e)
{
var list = new List<test>();
var assembly = Assembly.GetExecutingAssembly();
var resourceName = "XamarinDemo.test.csv";
using (Stream stream = assembly.GetManifestResourceStream(resourceName))
using (StreamReader reader = new StreamReader(stream))
{
//string result = reader.ReadToEnd();
if (reader != null)
{
using (var csv = new CsvReader(reader, CultureInfo.CurrentCulture))
{
while (csv.Read())
{
list.Add(new test
{
ID = csv.GetField<string>(0),
Name = csv.GetField<string>(1),
Age = csv.GetField<string>(2)
});
}
}
}
}
label.Text = (list.ToArray())[5].ID; //used to get the value of ID column,6th row(the row include the column[ID, Name, Age] row.).
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.