简体   繁体   中英

Epplus: When using LoadFromCollection, boolean column is blank in exported Excel file

In my MVC application, I have an ActionResult that loads an IEnumerable and exports it to an Excel File. That part works great, unless I have a boolean column. In that case, the values of the boolean column are blank.

Are boolean columns not supported by LoadFromCollection?

To resolve this, I could create a separate field in the model that translates the boolean value to a string value. However, I was hoping I could add a statement in the ExcelPackage() block that does the job without needing to adjust the model. Is this possible, or is rewriting the model the only possible solution?

public ActionResult ExportToExcel(string _searchString, string _setScale)
{                
   // This is the query result set the user wishes to export to file
   IEnumerable<CreditsAllsExport> exportQuery;
   /* ... irrelevant code redacted ... */
   exportQuery = exportQuery.AsEnumerable();

   byte[] response;
   using (var excelFile = new ExcelPackage())
   {
      /* ... irrelevant code redacted ... */
      worksheet.Cells["A5"].LoadFromCollection(Collection: exportQuery, PrintHeaders: true);

      /* TRANSLATE BOOLEAN TO Yes or No */

      response = excelFile.GetAsByteArray();
  }

  /* ... irrelevant code redacted ... */
}

This works perfectly fine...

        var rnd = new Random();

        var pkg = new ExcelPackage();
        var ws = pkg.Workbook.Worksheets.Add("Test");

        var blist = new List<bool>();
        for(int i=0; i < 20;i++) {
            blist.Add(rnd.NextDouble() > .5 ? true : false);
        }

        ws.Cells["A5"].LoadFromCollection(blist, true);

        pkg.SaveAs(new FileInfo(@"c:\tmp\bool.xlsx"));

This is embarrassing, but it turns out that my column didn't appear in the results because I had failed to include it in my select statement.

As @Izydrmr showed, boolean values are supported by LoadFromCollection. So the the take-home point is that if a boolean column doesn't appear, then check the select statement.

IEnumerable<CreditsAllsExport> exportQuery =
   from s in db.CreditsAlls
   select new CreditsAllsExport
   {
      FiscalYear = s.FiscalYear,
      Campus = s.Campus,
      StudentName = s.StudentName,
      CourseID = s.CourseID,
      CourseTitle = s.CourseTitle,
      CreditEarned = s.CreditEarned,
      DateEarned = s.DateEarned,
      Department = s.Department,
      School = s.School,
      Teacher = s.Teacher,
      /* I had forgotten this column*/ Transfer=s.Transfer,  
      CampusSchoolMatch = s.CampusSchoolMatch
  };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM