Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert CSV into XLS

Tags:

c#

csv

xls

I'm working in a web application separated in blocks and I'm getting a CSV object from a work mate of mine which I must convert into XLS to be passed into an Excel Processor they built. This CSV object is delimited by the character ";".

What I'd like to know is how I can convert the CSV object into XLS programatically.

like image 768
Hallaghan Avatar asked Jan 24 '11 11:01

Hallaghan


2 Answers

It should be easy for you to convert the CSV object into an array of arrays of strings and then do like in the following example (you'll need to add a reference to Microsoft.Office.Interop.Excel):

using Excel = Microsoft.Office.Interop.Excel;

Excel.Application excel = new Excel.Application();
Excel.Workbook workBook = excel.Workbooks.Add();
Excel.Worksheet sheet = workBook.ActiveSheet;

var CsvContent = new string[][]
{
    new string[] {"FirstName", "UserName", "PostCode", "City"},
    new string[] {"John", "Smith", "4568", "London"},
    new string[] {"Brian", "May", "9999", "Acapulco"}
};

for (int i = 0; i < CsvContent.Length; i++)
{
    string[] CsvLine = CsvContent[i];
    for (int j = 0; j < CsvLine.Length; j++)
    {
        sheet.Cells[i + 1, j + 1] = CsvLine[j];
    }
}

workBook.SaveAs(@"C:\Temp\fromCsv.xls");
workBook.Close();
like image 159
vc 74 Avatar answered Nov 04 '22 16:11

vc 74


Does the output need to be in the legacy XLS format? If XLSX is acceptable, EPPlus is a great .NET library for writing spreadsheets. The older excellibrary can produce XLS files.

Only a few lines of code should be necessary for parsing the CSV file (just be careful of double quotation marks) and writing the output spreadsheet.

like image 22
Quppa Avatar answered Nov 04 '22 18:11

Quppa