Let's start by creating a simple spreadsheet using C and the
Say that we have some data on monthly outgoings that we want to convert into an Excel XLSX file:
To do that we can start with a small program like the following:
If we run this program we should get a spreadsheet that looks like this:
This is a simple example but the steps involved are representative of all programs that use
libxlsxwriter, so let's break it down into separate parts.
The first step is to include the header for the library:
Then we need some data to add to the spreadsheet. For the sake of this example we create and initialize some simple data structures. In a real application the input data might come from a database or a file.
The next step is to create a workbook object in a
main block or function using the workbook_new() function which takes the filename that we want to create:
The workbook object is then used to add a new worksheet via the workbook_add_worksheet() function:
NULL pointer is used for the worksheet name then a default name will be supplied using the Excel convention of
Sheet2, etc. However we can also specify a name:
A1, is equivalent to
So in our example we iterate over our data and write it out as follows:
We then add a formula to calculate the total of the items in the second column:
Finally, we close the Excel file via the close method:
And that's it. We now have a file that can be read by Excel and other spreadsheet applications.
In the next sections we will see how we can use the
libxlsxwriter module to add formatting and other Excel features.