测试
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#ifndef _WIN32
#include <unistd.h>
#endif
#include "xlsxio_write.h"
#include "xlsxio_read.h"
int testWrite()
{
const char* filename = "example.xlsx";
xlsxiowriter handle;
//open .xlsx file for writing (will overwrite if it already exists)
if ((handle = xlsxiowrite_open(filename, "MySheet")) == NULL) {
fprintf(stderr, "Error creating .xlsx file\n");
return 1;
}
//set row height
xlsxiowrite_set_row_height(handle, 1);
//how many rows to buffer to detect column widths
xlsxiowrite_set_detection_rows(handle, 10);
//write column names
xlsxiowrite_add_column(handle, "Col1", 0);
xlsxiowrite_add_column(handle, "Col2", 21);
xlsxiowrite_add_column(handle, "Col3", 0);
xlsxiowrite_add_column(handle, "Col4", 2);
xlsxiowrite_add_column(handle, "Col5", 0);
xlsxiowrite_add_column(handle, "Col6", 0);
xlsxiowrite_add_column(handle, "Col7", 0);
xlsxiowrite_next_row(handle);
//write data
int i;
for (i = 0; i < 1000; i++) {
xlsxiowrite_add_cell_string(handle, "Test");
xlsxiowrite_add_cell_string(handle, "A b c d e f\nnew line");
xlsxiowrite_add_cell_string(handle, "&% <test> \"'");
xlsxiowrite_add_cell_string(handle, NULL);
xlsxiowrite_add_cell_int(handle, i);
xlsxiowrite_add_cell_datetime(handle, time(NULL));
xlsxiowrite_add_cell_float(handle, 3.1415926);
xlsxiowrite_next_row(handle);
}
//close .xlsx file
xlsxiowrite_close(handle);
return 0;
}
//callback data structure for listing sheets
struct xlsx_list_sheets_data {
char* firstsheet;
};
//callback function for listing sheets
int xlsx_list_sheets_callback(const char* name, void* callbackdata)
{
struct xlsx_list_sheets_data* data = (struct xlsx_list_sheets_data*)callbackdata;
if (!data->firstsheet)
data->firstsheet = strdup(name);
printf(" - %s\n", name);
return 0;
}
//callback function for end of row
int sheet_row_callback(size_t row, size_t maxcol, void* callbackdata)
{
printf("\n");
return 0;
}
//callback function for cell data
int sheet_cell_callback(size_t row, size_t col, const XLSXIOCHAR* value, void* callbackdata)
{
if (col > 1)
printf("\t");
if (value)
printf("%s", value);
return 0;
}
int testRead() {
const char* filename = "example.xlsx";
xlsxioreader xlsxioread;
//open .xlsx file for reading
if ((xlsxioread = xlsxioread_open(filename)) == NULL) {
fprintf(stderr, "Error opening .xlsx file\n");
return 1;
}
//list available sheets
struct xlsx_list_sheets_data sheetdata;
sheetdata.firstsheet = NULL;
printf("Available sheets:\n");
xlsxioread_list_sheets(xlsxioread, xlsx_list_sheets_callback, &sheetdata);
//read data
xlsxioread_process(xlsxioread, sheetdata.firstsheet, XLSXIOREAD_SKIP_EMPTY_ROWS, sheet_cell_callback, sheet_row_callback, NULL);
//clean up
free(sheetdata.firstsheet);
xlsxioread_close(xlsxioread);
return 0;
}
void test() {
testWrite(); // 测试写入
testRead(); // 测试读取
}
输出
文件结构
写
读
参考
GitHub - brechtsanders/xlsxio: XLSX I/O - C library for reading and writing .xlsx files