Reputation: 153
I'm trying to generate a CSV file from excel files. I have different Excel files and I would like to read them and generate a CSV file. I imagine it must be quite easy, but I'm having some trouble.
This is the library I'm supposed to use
I would appreciate any tutorial or anything on how I can approach this matter. The idea is to read the first row of my Excel files like headers and then the other rows as values, so I can write the CSV.
Upvotes: 0
Views: 5901
Reputation: 1332
public class Program
{
public static void Main()
{
string filePath = "C:\\Users\\{User}\\Desktop\\sample.xlsx";
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
List<List<object>> rows = new List<List<object>>();
List<object> row = new List<object>();
// Excel Reader
using (var stream = File.Open(filePath, FileMode.Open, FileAccess.Read))
{
using (var reader = ExcelReaderFactory.CreateReader(stream, new ExcelReaderConfiguration
{
FallbackEncoding = Encoding.GetEncoding(1252),
}))
{
do
{
while (reader.Read())
{
row.Clear();
for (int i = 0; i < reader.FieldCount; i++)
{
var field = reader.GetValue(i);
if (field is int valueInt)
{
row.Add(valueInt);
}
else if (field is bool valueBool)
{
row.Add(valueBool);
}
else if (field is DateTime valueDate)
{
//row.Add(valueDate); You can write any condition there
row.Add(valueDate.Year);
}
else if (field is TimeSpan valueTime)
{
row.Add(valueTime);
}
else if (field is string valueString)
{
row.Add(valueString);
}
else if (field is null)
{
row.Add(field);
}
}
if (row.Any())
{
rows.Add(row);
}
}
} while (reader.NextResult());
}
}
// CSV Writer
using (var writer = new StreamWriter("C:\\Users\\{User}\\Desktop\\sample.csv"))
using (var csv = new CsvWriter(writer))
{
foreach (var i in rows)
{
foreach (var field in i)
{
csv.WriteField(field);
}
csv.NextRecord();
}
}
}
}
This program convert Excel (sample.xlsx) file to CSV(sample.csv) File.
Dependencies :
Upvotes: 2
Reputation: 47
Create a class file that would contain attributes which are same to that of your excel columns. Parse through your excel files and load it into the instance of your class. Write a simple program as follows
void Main()
{
var records = new List<Foo>
{
new Foo { Id = 1, Name = "one" },
};
using (var writer = new StreamWriter("path\\to\\file.csv"))
using (var csv = new CsvWriter(writer))
{
csv.WriteRecords(records);
}
}
public class Foo
{
public int Id { get; set; }
public string Name { get; set; }
}
Where Foo is the class file. Hope this helps
Upvotes: -1