使用c#中的CSVHelper更改CSV文件中的标题名称
本文关键字:标题 文件 CSV 中的 CSVHelper 更改 使用 | 更新日期: 2023-09-27 17:49:24
我使用CSV Helper库为用户生成CSV文件填充并上传到系统。我的问题是,WriteHeader方法只是写的属性类的名称,如"PropertyValue",这是不友好的用户。是否有一种方法,我可以使用,使产生的文本用户友好,但仍然能够成功地将类映射到文件的数据?
我的代码如下所示:
public ActionResult UploadPropertyCSV(HttpPostedFileBase file)
{
List<PropertyModel> properties = new List<PropertyModel>();
RIMEDb dbContext = new RIMEDb();
bool success = false;
foreach (string requestFiles in Request.Files)
{
if (file != null && file.ContentLength > 0 && file.FileName.EndsWith(".csv"))
{
using(StreamReader str = new StreamReader(file.InputStream))
{
using(CsvHelper.CsvReader theReader = new CsvHelper.CsvReader(str))
{
while (theReader.Read())
{
RIMUtil.PropertyUploadCSVRowHelper row = new RIMUtil.PropertyUploadCSVRowHelper()
{
UnitNumber = theReader.GetField(0),
StreetNumber = theReader.GetField(1),
StreetName = theReader.GetField(2),
AlternateAddress = theReader.GetField(3),
City = theReader.GetField(4)
};
Property property = new Property();
property.UnitNumber = row.UnitNumber;
property.StreetNumber = row.StreetNumber;
property.StreetName = row.StreetName;
property.AlternateAddress = row.AlternateAddress;
property.City = dbContext.PostalCodes.Where(p => p.PostalCode1 == row.PostalCode).FirstOrDefault().City;
dbContext.Properties.Add(property);
try
{
dbContext.SaveChanges();
success = true;
}
catch(System.Data.Entity.Validation.DbEntityValidationException ex)
{
success = false;
RIMUtil.LogError("Ptoblem validating fields in database. Please check your CSV file for errors.");
}
catch(Exception e)
{
RIMUtil.LogError("Error saving property to database. Please check your CSV file for errors.");
}
}
}
}
}
}
return Json(success);
}
我想知道是否有一些元数据标签或者我可以在我的PropertyUploadCSVRowHelper类的每个属性的顶部放置我想要在文件
中生成的文本Thanks in advance
不确定2年前是否存在,但现在,我们可以使用以下属性函数更改属性/列名:
[CsvHelper.Configuration.Attributes.Name("Column/Field Name")]
完整代码:
using CsvHelper;
using System.Collections.Generic;
using System.IO;
namespace Test
{
class Program
{
class CsvColumns
{
private string column_01;
[CsvHelper.Configuration.Attributes.Name("Column 01")] // changes header/column name Column_01 to Column 01
public string Column_01 { get => column_01; set => column_01 = value; }
}
static void Main(string[] args)
{
List<CsvColumns> csvOutput = new List<CsvColumns>();
CsvColumns rows = new CsvColumns();
rows.Column_01 = "data1";
csvOutput.Add(rows);
string filename = "test.csv";
using (StreamWriter writer = File.CreateText(filename))
{
CsvWriter csv = new CsvWriter(writer);
csv.WriteRecords(csvOutput);
}
}
}
}
这可能不会直接回答你的问题,因为你说你想使用csvhelper,但如果你只写小尺寸的文件(这是一个简单的函数,我用来生成csv。注意,csvhelper对于更大的文件会更好,因为它只是构建一个字符串,而不是流数据。
只需在变量下面的代码中自定义列数组以满足您的需要。
public string GetCsv(string[] columns, List<object[]> data)
{
StringBuilder CsvData = new StringBuilder();
//add column headers
string[] s = new string[columns.Length];
for (Int32 j = 0; j < columns.Length; j++)
{
s[j] = columns[j];
if (s[j].Contains("'"")) //replace " with ""
s[j].Replace("'"", "'"'"");
if (s[j].Contains("'"") || s[j].Contains(" ")) //add "'s around any string with space or "
s[j] = "'"" + s[j] + "'"";
}
CsvData.AppendLine(string.Join(",", s));
//add rows
foreach (var row in data)
{
for (int j = 0; j < columns.Length; j++)
{
s[j] = row[j] == null ? "" : row[j].ToString();
if (s[j].Contains("'"")) //replace " with ""
s[j].Replace("'"", "'"'"");
if (s[j].Contains("'"") || s[j].Contains(" ")) //add "'s around any string with space or "
s[j] = "'"" + s[j] + "'"";
}
CsvData.AppendLine(string.Join(",", s));
}
return CsvData.ToString();
}
下面是如何使用它的一个简单示例:https://dotnetfiddle.net/2WHf6o
好运。