brechtsanders / xlsxio

XLSX I/O - C library for reading and writing .xlsx files
MIT License
397 stars 113 forks source link

A way to write multiple strings to the cell #124

Closed roda37 closed 8 months ago

roda37 commented 8 months ago

Below is a quick and dirty example of how to make this library as useful as possible! However is there a way to save items to the buffer and save them all at once to the output file? In the example below only the last one will be saved to the buffer and hence written to the output file. What I am asking is if there is a way to append the written cells to the buffer where it will be saved all at once?

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "include/xlsxio_write.h"
#define MAX_LEN 1000

const char* filename = "report.xlsx"; // set filename of the final output file

void xlsx(int row, int col, char* data) {
    xlsxiowriter handle;

    if ((handle = xlsxiowrite_open(filename, "example xlsx")) == NULL) {
        fprintf(stderr, "Error creating xlsx \n");
        exit(1);
    }

    xlsxiowrite_set_row_height(handle, 1); // set height
    xlsxiowrite_set_detection_rows(handle, 10); //how many rows to buffer to detect column width

    int i;
    for (i = 1; i < MAX_LEN; i++) {
        if (i == row) {
            for (int s = 1; s < MAX_LEN; s++) { // check for column
                if (s == col) {
                    xlsxiowrite_add_column(handle, data, 10);
                } else {
                    xlsxiowrite_add_column(handle, "", 10); // if not row, write empty string in row (skip it)
                }
            }
        } else {
            xlsxiowrite_add_cell_string(handle, ""); // if not row, write empty string in row (skip it)
            xlsxiowrite_next_row(handle);
        }
    }

    xlsxiowrite_close(handle); //close xlsx file
}

int main() {
    xlsx(5, 2, "hello");
    xlsx(10, 3, "there");
    xlsx(8, 8, "mate");
    return 0;
}
brechtsanders commented 8 months ago

The whole idea aboit the XLSX I/O library is to be able to read/write data sequentially, avoiding having all the contents in memory.

In your example you jump back to a previous line, which will cause unexpected behavior.

If you want that you should either prepare all the data in memory, or use a different library that does everything in memory and only writes at the end.

Why don't you just populata a 2-dimensional array and save it once all data is populated?