Convert CSV into XLS

后端 未结 5 1352
孤城傲影
孤城傲影 2020-12-29 15:25

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 Process

5条回答
  •  生来不讨喜
    2020-12-29 16:07

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

提交回复
热议问题