Dev
Dev

Reputation: 1826

How to use Boolean values as check box values in Excel from C#

I am trying to send boolean values from my WPF C# app to a Xcel file but the content is showing 'TRUE' and 'FALSE' as text instead of checkboxes.

C# Model:

public class ExcelModel
{
    public string ID { get; set; }
    public string Title { get; set; }
    public bool IsHotel { get; set; }

}

C# Code:

var dataList = new List<ExcelModel>() { new ExcelModel{ID = "1", Title = "Test1", IsHotel = True} };    

var workbook = new XLWorkbook();     //creates the workbook
var wsDetailedData = workbook.AddWorksheet("Test"); //creates the worksheet with sheetname 'data'

wsDetailedData.Cell(1, 1).InsertTable(dataList); //inserts the data to cell A1 including default column name

wsDetailedData.Columns().AdjustToContents();

// wsDetailedData.Column.
wsDetailedData.Rows().AdjustToContents();
workbook.SaveAs(MainWindow.appRoot + @"test.xlsx"); //saves the workbook

Upvotes: 1

Views: 2471

Answers (1)

VB Did Nothing Wrong
VB Did Nothing Wrong

Reputation: 385

This isn't possible from the ClosedXML library, which you seem to be using.

It is possible if you use Microsoft.Office.Interop.Excel to create the excel. (But you would need office installed on the computer running your program). See:

https://stackoverflow.com/a/8936775/994679

If that's not acceptable, it ought to be possible using OpenXml instead. But you'd really have your work cut out for you, and I can't find any simple examples of doing that. Here's an example of a guy adding a Combobox:

https://social.msdn.microsoft.com/Forums/vstudio/en-US/4489302b-57a0-434f-b7ed-d8bb6479edf0/how-to-insert-a-combobox-in-a-spreadsheet-by-code-behind-c-using-open-xml-format-sdk?forum=oxmlsdk

You might be able to find out the code if you're using OpenXml by using the OpenXml Productivity tool. There you can create an excel with a checkbox, and use the Reflect Code button to generate the OpenXml code to use, though it will probably still be challenging to find the specific generated code you need to use, and understand how to adapt it properly.

Upvotes: 1

Related Questions