Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ClosedXML Adding Data to Existing Table

With ClosedXML I am trying to add data to an existing Excel Sheet In an Existing Table. The easy thing to do is to add a table to an excel sheet below is a quick example of how to do that. What I don't understand is if you already have a Table there that is empty how can you just add to the existing table?

// Add a DataTable as a worksheet
            wb.Worksheets.Add(dataTable);
like image 488
scripter78 Avatar asked Aug 11 '15 17:08

scripter78


People also ask

What is the difference between OpenXml and ClosedXML?

Macros – ClosedXml doesn't support macros as its base library OpenXml also doesn't support it. Embedding – We cannot embed any file into Excel using ClosedXml, no APIs built for that, so some features of OpenXml still need to be implemented. Charts – No functionality related to charting is present.

How do you create a datatype for a column in ClosedXML?

ClosedXML sets the data type for all cells in the column, down to the maximum (row 1 million or so). Use this to only set the data type for the used cells in the column: ws. Column(1).

Does ClosedXML support XLS?

ClosedXML is a . NET library for reading, manipulating and writing Excel 2007+ (. xlsx, . xlsm) files.


2 Answers

I don't know how this question isn't clear to people. If there is an existing Table (created in Excel by going to "Insert -> Table") and you open an Excel document using ClosedXML, adding data to the next row does not automatically expand the Table.

You can expand it prior to adding the data as such:

IXLTables tsTables = thisSheet.Tables;
IXLTable firstTable = tsTables.FirstOrDefault();
if (firstTable != null)
    firstTable.InsertRowsBelow(1);
like image 134
AndrewK Avatar answered Sep 17 '22 11:09

AndrewK


I had a similar requirement, where I needed to insert data into an existing Table, which had a number of data validations / comments / formula built in.

I found that the easiest solution (for me) was to use the Table's ReplaceData call. This is particularly useful if you provide a name for your Table in the Excel worksheet, as that way you can get a reference to the table directly from the workbook, ie:

var candidateTable = workbook.Table("Candidates");  
candidateTable.ReplaceData(candidateData, propagateExtraColumns: true);

Note that the key to getting this to work properly is to set the propogateExtraColumns parameter - this will ensure any formula / etc you have set will automatically be copied to any new rows that are created.

FYI - you can set the Excel Table's name by selecting your table in the worksheet, clicking the Design tab, and then entering a table name:

Enter table name in Excel

like image 45
RMD Avatar answered Sep 17 '22 11:09

RMD