本文介绍了重新格式化csv文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
hi,
i have a csv file that i want to reformat into a new csv :
source :
H;billythekid;25;male;book;SF;Western Fiction;11/10/2002;;Edition;;Library;
L;302;1;15;paragraph;12
L;412;2;23;paragraph;6
... etc
and i want that it becomes like that :
H;billythekid;25;male;book ;SF;Western Fiction ;11/10/2002;;Edition;;Library;
L;302;1;15 ;paragraph;12
L;412;2;23 ;paragraph;6
i have this code:
try
{
using (StreamReader sr = new StreamReader(filename)
{
using (StreamWriter sw = new StreamWriter(newfilename)
{
string line;
while ((line = sr.ReadLine())!= null )
{
if (line.StartsWith("H;"))
{
list = line.Split(';').ToList();
sw.WriteLine(line);
}
else
{
list = line.Split(';').ToList();
list.Add(line);
sw.WriteLine(line);
}}}}
catch (Exeption Ex)
{}
推荐答案
using System;
using System.Collections.Generic;
using System.IO;
namespace ParseTest {
class Program {
private static bool IsHeader(string line) {
return line.StartsWith("H;");
}
private static void OutputColumns(StreamWriter output, string line, char delimiter, int[] minColumnWidths) {
IList<string> columns = new List<string>();
var tokens = line.Split(delimiter);
for (var i = 0; i < tokens.Length; ++i)
{
var formatString = string.Format("{{0,-{0}}}", i < minColumnWidths.Length ? minColumnWidths[i] : 1);
columns.Add(string.Format(formatString, tokens[i]));
}
output.WriteLine(String.Join(delimiter.ToString(), columns));
}
public static void Main(string[] args)
{
var headerMinWidths = new[] {1, 1, 1, 1, 10, 1, 23, 1, 1, 1, 1, 1};
var dataMinWidths = new[] {1, 1, 1, 11, 1, 1, 1, 1, 1, 1, 1, 1};
using(var input = new StreamReader(@"C:\Temp\input.txt")) {
using (var output = new StreamWriter(@"C:\Temp\output.txt"))
{
string line;
while ((line = input.ReadLine()) != null) {
OutputColumns(output, line, ';', IsHeader(line) ? headerMinWidths : dataMinWidths);
}
}
}
}
}
}
希望这会有所帮助,
Fredrik
Hope this helps,
Fredrik
这篇关于重新格式化csv文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!