我已编写此代码来读取和写入CSV文件。有没有办法可以跳过将第一行写为标题,我想将自己的标题写入新文件。这就是我到目前为止所做的事情
try
{
using (StreamWriter sw = new StreamWriter("C:/Projects/data/PYAEGON1AEGONRESULT.csv"))
using (StreamReader sr = new StreamReader("C:/Projects/data/PYAEGON1AEGON.csv"))
{
heading = "Title, First Name, Surname, Date Of Birth, NI Number, Gender, Payroll Reference, Address Line 1, Address Line 2, Address Line 3, Address Line 4, AddressLine 5, PostCode, Country, Email, Date Joined Employer, Annual Pensionable Salary, Current Period All Earnings (Monthly), Current Period Pensionable Earnings (Monthly), Emnployee (Amount Deducted), Employer (Amount Deducted), Leaving Date.";
sw.WriteLine(heading);
while((txtline = sr.ReadLine()) != null)
{
oldcolumns = Regex.Split(txtline,",");
newcolumns[0] = oldcolumns[0];
newcolumns[1] = oldcolumns[1];
newcolumns[2] = oldcolumns[2];
newcolumns[3] = oldcolumns[3];
newcolumns[4] = oldcolumns[4];
newcolumns[5] = oldcolumns[5];
newcolumns[6] = oldcolumns[6];
newcolumns[7] = oldcolumns[7];
newcolumns[8] = oldcolumns[9];
newcolumns[9] = oldcolumns[10];
newcolumns[10] = oldcolumns[11];
newcolumns[11] = "";
newcolumns[12] = oldcolumns[12];
newcolumns[13] = "United Kingdom";
newcolumns[14] = oldcolumns[14];
newcolumns[15] = oldcolumns[15];
newcolumns[16] = oldcolumns[16];
newcolumns[17] = oldcolumns[17];
newcolumns[18] = oldcolumns[18];
newcolumns[19] = oldcolumns[19];
newcolumns[20] = oldcolumns[20];
newcolumns[21] = "";
csvline = "";
for (int i = 0; i < 21; i++)
{
csvline = csvline + "\"" + newcolumns[i].Replace("\"","") + "\",";
}
sw.WriteLine(csvline);
}
答案 0 :(得分:1)
如果您不想在开始写作之前使用sr.ReadLine()
编写第一行。这使读者进入第二行。
using (StreamWriter sw = new StreamWriter("C:/Projects/data/PYAEGON1AEGONRESULT.csv"))
using (StreamReader sr = new StreamReader("C:/Projects/data/PYAEGON1AEGON.csv"))
{
sr.ReadLine();
// the next ReadLine will read the second line as desired
heading = "Title, First Name, Surname, Date Of Birth, NI Number, Gender, Payroll Reference, Address Line 1, Address Line 2, Address Line 3, Address Line 4, AddressLine 5, PostCode, Country, Email, Date Joined Employer, Annual Pensionable Salary, Current Period All Earnings (Monthly), Current Period Pensionable Earnings (Monthly), Emnployee (Amount Deducted), Employer (Amount Deducted), Leaving Date.";
sw.WriteLine(heading);
while((txtline = sr.ReadLine()) != null)
{
// ...
sw.WriteLine(csvline);
// ...
答案 1 :(得分:0)
在实际开始阅读输入之前,只需致电sr.ReadLine()
。
using (StreamWriter sw = new StreamWriter("C:/Projects/data/PYAEGON1AEGONRESULT.csv"))
using (StreamReader sr = new StreamReader("C:/Projects/data/PYAEGON1AEGON.csv"))
{
sr.ReadLine();
// rest of your code