赞
踩
1.在github上下载源码:https://github.com/jmcnamara/libxlsxwriter
2.解压后放入项目中
file(GLOB SRC "*.cpp") message(STATUS "SRC: ${SRC}") set(TARGET exportXlsx) # 将libxlsxwriter库作为子文件夹引入项目 add_subdirectory(libxlsxwriter) # 设置xlsx的导出目录 set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${EMS_ROOT}/xlsx) message(STATUS "CMAKE_RUNTIME_OUTPUT_DIRECTORY: ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}") # 添加可执行文件 add_executable(${TARGET} ${SRC}) set(XLSX_INCLUDE_DIRS "${CMAKE_CURRENT_SOURCE_DIR}/libxlsxwriter/include/") message(STATUS "XLSX_INCLUDE_DIRS: ${XLSX_INCLUDE_DIRS}") # 链接库头文件目录 target_include_directories(${TARGET} PUBLIC ${XLSX_INCLUDE_DIRS}) # 链接库 target_link_libraries(${TARGET} PUBLIC xlsxwriter)
新建xlsx文件,并设置格式
lxw_workbook* workbook = workbook_new("test.xlsx");
lxw_worksheet* worksheet = workbook_add_worksheet(workbook, NULL);
lxw_format* format = workbook_add_format(workbook);
// 设置水平对齐方式为居中
format_set_align(format, LXW_ALIGN_CENTER);
// 设置垂直对齐方式为居中
format_set_align(format, LXW_ALIGN_VERTICAL_CENTER);
设置单元格的宽度和格式
// 设置 startCol-endCol 列的宽度和格式
int startCol=1,endCol=10;
worksheet_set_column(worksheet, startCol, endCol, 20, format);
将数据写入单元格
// 写入string类型到第0行第0列单元格
std::string str = "Hello";
worksheet_write_string(worksheet, 0, 0, str.c_str(), NULL);
// 将数字类型写入单元格,支持整型和浮点型
worksheet_write_number(worksheet, 2, 0, 123, NULL);
worksheet_write_number(worksheet, 3, 0, 123.456, NULL);
// 单元格里设置图片
worksheet_insert_image(worksheet, 1, 2, "logo.png");
// 合并第0行 col-col2 列的单元格,设置值为"哈哈"
worksheet_merge_range(worksheet, 0, col1, 0, col2, "哈哈", format);
// 合并第0列的 row1 ~ row2 行的单元格,设为日期
worksheet_merge_range(worksheet, row1, 0, row2, 0, "日期", this->format);
关闭workbook
// 使用完后需要关闭
workbook_close(this->workbook);
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。