我正在读取XLS文件并将数字(从excel = currow的当前行)传递给在新csv文件中创建对象的方法:
public class Importer
...
IList<NewDataObj> n_obj = new List<NewDataObj>();
foreach (var item in data.AsEnumerable().Where(o => o.Field<string>("MyID") == ImportID)){
n_obj.Add(new NewDataObj(item, ID, currow));
currow++;}
....
创建新DataObj的方法:
public class NewDataObj{
....
public static string_1 = "\"{3}\";\"NEW_OBJECT\";\"TEST\"{5}\";
public static string_2 = "\"{3}\";\"NEW OBJECT\";\"TEST_A2\"{5}\";
public double DataID { get; set; }
.....
public NewDataObj(DataRow item, string newID, int currow){
....
ID = string.Format("{{ABC_TEST_{0:000}}}", currow);
AddtoFile_A();
//AddtoFile_A2();
}
public void AddtoFile_A(){
using (StreamWriter w = File.AppendText("testX.csv"))
{
w.WriteLine(string.Format(string_1, DataID, ID, Environment.NewLine));
}
}
}
这工作正常,但现在我不得不添加AddtoFile_A2方法。
public void AddtoFile_A2(){
using (StreamWriter w = File.AppendText("testX.csv"))
{
w.WriteLine(string.Format(string_2, DataID, ID, Environment.NewLine));
}
}
并且AddtoFile_A2也使用相同的currow。对我来说,当执行AddtoFile_A或AddtoFile_A2时,ID应该总是增加1。
怎么做?也许我的AddtoFile方法应该返回Importer类的值?
使用CsvHelper而不是用手写csv。
var data = new[] {
new BuisnessObject{ Id=1, Name="FOO" },
new BuisnessObject{ Id=2, Name="BAR" }
};
if (data.Any())
{
// RowNumber=index or RowNumber=index+1
var ouputs = data.Select(
(item, index) =>
new OuputType {
Id=item.Id,
Name=item.Name,
RowNumber=index
}
);
using (TextWriter writer = new StreamWriter($"OuputFileName.csv"))
using (var csv = new CsvWriter(writer))
{
csv.Configuration.RegisterClassMap<TestMap>();
csv.WriteHeader<OuputType>();
csv.NextRecord();
csv.WriteRecords(ouputs);
}
}
public sealed class BuisnessObject
{
public int Id { get; set; }
public string Name { get; set; }
}
public sealed class OuputType
{
public int Id { get; set; }
public string Name { get; set; }
public int RowNumber { get; set; }
}
public sealed class TestMap : ClassMap<OuputType>
{
public TestMap()
{
Map(m => m.Id);
Map(m => m.Name);
Map(m => m.RowNumber);
}
}
您可以通过在TestMap类中移动地图来对列进行排序。或者使用.Name("PrettyName")
更改名称
刚从我的同事那里得到答案 - 应该作为ref int currow
传递:
public class Importer
...
IList<NewDataObj> n_obj = new List<NewDataObj>();
foreach (var item in data.AsEnumerable().Where(o => o.Field<string>("MyID") == ImportID)){
n_obj.Add(new NewDataObj(item, ID, ref currow));//one change
currow++;}
....
并进入方法:
public class NewDataObj{
.....
public NewDataObj(DataRow item, string newID, ref int currow){ //second changes
....
ID = string.Format("{{ABC_TEST_{0:000}}}", currow);
AddtoFile_A();
currow++; //next changes
ID = string.Format("{{ABC_TEST_{0:000}}}", currow); //new id
AddtoFile_A2();
}
刚刚测试并且工作正常。