下载OpenXLSX
可以自己去GitHub下载,也可以下载我当前使用的版本,下载链接:OpenXLSA
文件提取
解压后,只需要OpenXLSX里的OpenXLSX文件,即不需要示例等,如下图把上述文件的文件夹拷贝到项目根目录下
配置工程
我这里使用的是Clion,只需要配置CMakeLists.txt就行,将下面内容粘贴到你的CMakeLists.txt中
# Set the build output location to a common directory
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/output)
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/output)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/output)
add_subdirectory(OpenXLSX)
target_link_libraries(word_tool_v1_0 OpenXLSX::OpenXLSX)
我的工程看起来下面这样的,可根据你自己实际配置
cmake_minimum_required(VERSION 3.25)
project(word_tool_v1_0)
set(CMAKE_CXX_STANDARD 17)
# Set the build output location to a common directory
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/output)
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/output)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/output)
add_subdirectory(OpenXLSX)
add_executable(word_tool_v1_0 main.cpp)
target_link_libraries(word_tool_v1_0 OpenXLSX::OpenXLSX)
读取
过程大致分为打开文件和读取指定单元格那么代码如下所示
#pragma warning(push)
#pragma warning(disable : 4244)
#include <OpenXLSX.hpp>
#include <iostream>
#include <numeric>
#include <random>
#include <XLCell.hpp>
#include <XLWorkbook.hpp>
#include <XLCellValue.hpp>
#include <string>
#include <sstream>
using namespace std;
using namespace OpenXLSX;
int main()
{
cout << "Start ..." << endl;
XLDocument doc;
doc.open("D://xxxx//test3.xlsx");
auto wks = doc.workbook().worksheet("Sheet1");
// 读取指定单元格
std::string cellAddress = "B3";
XLCell cell = wks.cell(cellAddress);
int cell_int_value = cell.value();
std::cout << "value " << cellAddress << " is: " << cell_int_value << endl;
doc.close();
return 0;
}
#pragma warning(pop)
实际上一个excel文件单元格数据类型是多种多样的,所以需要先判断类型,参考如下,目前只做了部分类型适配
#pragma warning(push)
#pragma warning(disable : 4244)
#include <OpenXLSX.hpp>
#include <iostream>
#include <numeric>
#include <random>
#include <XLCell.hpp>
#include <XLWorkbook.hpp>
#include <XLCellValue.hpp>
#include <string>
#include <sstream>
using namespace std;
using namespace OpenXLSX;
int main()
{
std::string cell_str;
int cell_int_value;
float cell_float_value;
XLDocument doc;
cout << "Start ..." << endl;
doc.open("D://pangjiazuo//test3.xlsx");
auto wks = doc.workbook().worksheet("Sheet1");
// 读取指定单元格
std::string cellAddress = "B3";
XLCell cell = wks.cell(cellAddress);
// 获取单元格数据类型
switch (cell.value().type()) {
case XLValueType::Empty:
break;
case XLValueType::Boolean:
break;
case XLValueType::Integer:
cell_int_value = cell.value();
cell_str = to_string(cell_int_value);
break;
case XLValueType::Float:
cell_float_value = cell.value();
cell_str = to_string(cell_int_value);
break;
case XLValueType::String:
break;
default:
break;
}
std::cout << "value " << cellAddress << " is: " << cell_str << endl;
doc.close();
return 0;
}
#pragma warning(pop)