Search code examples
c#excelepplus

I am reading in a CSV file and getting a Column out of range error


I am currently using EPPlus library and I am trying to read a csv file from a directory. I am finding the file and trying to save it as an Excel but I am getting an exception Column out of range when I am trying to save it.

    string csvPath = path;
        string expath = "C:\\Users\\er4505\\Desktop\\Test CSV File";

        string exWorksheet = "Test99999";
        bool firstRowIsHeader = false;

        var xformat = new ExcelTextFormat();
        xformat.Delimiter = ',';

        var excelInfo = new FileInfo(expath);
        var csvFileInfo = new FileInfo(csvPath);

        try {
            using (ExcelPackage csvToExcel = new ExcelPackage(excelInfo))
            {
                ExcelWorksheet worksheet = csvToExcel.Workbook.Worksheets.Add(exWorksheet);
                worksheet.Cells["A1"].LoadFromText(csvFileInfo,xformat,OfficeOpenXml.Table.TableStyles.Medium25, firstRowIsHeader);
                csvToExcel.Save();

            }
        }

Solution

  • Ok guys spent last night going through all the documentation on this library. This library is capable of receiving a list with out formatting it with comma separation. I simply passed in my query result list and the library did the rest.

    List<Engagement> QueryResult = PMService.GetRequestedEngagments(test);
    
    var filename = yourfilename;
    var path = @"C:\Users\er4505\Downloads" + filename;
    var excelFileInfo = new FileInfo(path);         
    
    try
    {
        using (ExcelPackage csvToExcel = new ExcelPackage())
        {
            ExcelWorksheet worksheet = csvToExcel.Workbook.Worksheets.Add(filename);
            worksheet.Cells["A1"].LoadFromCollection(QueryResult, true, OfficeOpenXml.Table.TableStyles.Medium25);
            csvToExcel.SaveAs(excelFileInfo);
        }
    }