Reputation: 75
I have few CSV file contains different data, I want to combine all this csv file into one ultimate CSV file which contains multiple sheets, under which this multiple csv are accommodated. Till now my below code picks data from the directory and combines all CSV file into one big CSV file where it is appending the data which i do not want, instead I want multiple sheet in one file..
private void combineallcsv()
{
string txtConsolidated_OS_CSV = "C:\\NWDLS\\new";
if (txtConsolidated_OS_CSV != "")
{
int counter = 0;
string[] files = (Directory.GetFiles(txtConsolidated_OS_CSV.Trim()));
foreach (var file in files)
{
StringBuilder sb = new StringBuilder();
string filename = Path.GetFileNameWithoutExtension(file);
if (file.EndsWith(".csv"))
{
string[] rows = File.ReadAllLines(file);
for (int i = 0; i < rows.Length; i++)
{
if (i == 0)
{
if (counter == 0)
{
sb.Append(rows[i] + "\n");
counter++;
}
}
else
{
sb.Append(rows[i] + "\n");
}
}
}
string csvfile = txtConsolidated_OS_CSV + "\\Merged_OS.csv";
if (File.Exists(csvfile))
{
File.AppendAllText(csvfile, sb.ToString());
sb.Clear();
}
else
{
File.WriteAllText(csvfile, sb.ToString());
sb.Clear();
}
//using (StreamWriter writer = new StreamWriter(csvfile, true))
//{
// writer.Write(sb.ToString());
// writer.Dispose();
// writer.Close();
//}
}
counter = 0;
}
}
Upvotes: 0
Views: 896
Reputation: 56697
There's not such thing as "sheets" in CSV files. CSV files are just lines of text where fields are separated by some defined character. That's all.
You can use VSTO office interop or ADO.NET drivers to create "real" Excel sheets.
Upvotes: 2