How to read data from an excel table in C?

Asked

Viewed 1,675 times

1

I know how to read data and write to files .txt code C through functions fscanf(), fprintf() etc. But now I would like to know if there are functions or libraries in C that allow me to process data from a table excel, where I can access columns and rows, if anyone knows, you could let me know?

1 answer

3


There is the library Libxl, but she gets paid.

Example: generate a spreadsheet from scratch

#include "libxl.h"


int main()
{
    BookHandle book = xlCreateBook(); // xlCreateXMLBook()
    if(book) 
    {
        SheetHandle sheet = xlBookAddSheet(book, L"Sheet1");
        if(sheet) 
        {
            xlSheetWriteStr(sheet, 2, 1, L"Hello, World !", NULL);
            xlSheetWriteNum(sheet, 3, 1, 1000, NULL);
        }
        xlBookSave(book, L"example.xls");
        xlBookRelease(book);
    }
    return 0;
}

An alternative open source and free is the library XLSX I/O.

Example

//open .xlsx file for reading
xlsxioreader xlsxioread;
if ((xlsxioread = xlsxioread_open(filename)) == NULL) {
  fprintf(stderr, "Error opening .xlsx file\n");
  return 1;
}

//list available sheets
xlsxioreadersheetlist sheetlist;
const char* sheetname;
printf("Available sheets:\n");
if ((sheetlist = xlsxioread_sheetlist_open(xlsxioread)) != NULL) {
  while ((sheetname = xlsxioread_sheetlist_next(sheetlist)) != NULL) {
    printf(" - %s\n", sheetname);
  }
  xlsxioread_sheetlist_close(sheetlist);
}

//read values from first sheet
char* value;
printf("Contents of first sheet:\n");
xlsxioreadersheet sheet = xlsxioread_sheet_open(xlsxioread, NULL, XLSXIOREAD_SKIP_EMPTY_ROWS);
while (xlsxioread_sheet_next_row(sheet)) {
  while ((value = xlsxioread_sheet_next_cell(sheet)) != NULL) {
    printf("%s\t", value);
    free(value);
  }
  printf("\n");
}
xlsxioread_sheet_close(sheet);

//clean up
xlsxioread_close(xlsxioread);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.