Convert CSV into XLS

╄→尐↘猪︶ㄣ 提交于 2019-11-30 05:18:05

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();

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.

One option is to use a 3rd party library to create the XLS file, and the other is to use COM interop to manipulate Excel into opening the CSV file and save it as XLS.

David Yenglin

Would this C# Excel import data from CSV into Excel help? It seems to address what you need to do.

    using Excel = Microsoft.Office.Interop.Excel;

    public void Convert_CSV_To_Excel()
    {

        // Rename .csv To .xls
        System.IO.File.Move(@"d:\Test.csv", @"d:\Test.csv.xls");

        var _app = new Excel.Application();
        var _workbooks = _app.Workbooks;

        _workbooks.OpenText("Test.csv.xls",
                                 DataType: Excel.XlTextParsingType.xlDelimited,
                                 TextQualifier: Excel.XlTextQualifier.xlTextQualifierNone,
                                 ConsecutiveDelimiter: true,
                                 Semicolon: true);
        // Convert To Excle 97 / 2003
        _workbooks[1].SaveAs("NewTest.xls", Excel.XlFileFormat.xlExcel5);

        _workbooks.Close();
    }
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!