使用LibXL 库。
LibXL可以不依赖EXCEL读取XLS和XLSX文件,支持多语言平台,使用也挺方便的。
参考:https://blog.csdn.net/zt_xcyk/article/details/72846042
C++工程创建:
Vs2019->c++控制台应用
动态库环境配置:
设置包含目录和库目录,库目录根据x32/x64选择对映的lib/lib64
遇到Error
需要把bin/bin64下的libxl.dll拷贝到工程里
直接粘贴程序代码:
#include <iostream>
#include <locale.h>
#include <windows.h>
#include "libxl.h"
#pragma comment(lib,"libxl.lib")
using namespace libxl;
using namespace std;
void WcharToString(string& szDst, const wchar_t* wchar)
{
DWORD dwNum = WideCharToMultiByte(CP_OEMCP, NULL, wchar, -1, NULL, 0, NULL, FALSE);
char* psText;
psText = new char[dwNum];
WideCharToMultiByte(CP_OEMCP, NULL, wchar, -1, psText, dwNum, NULL, FALSE);
szDst = psText;
delete[]psText;
}
//不要忘记在使用完wchar_t*后delete[]释放内存
wchar_t* StringToWchar(const string& pKey)
{
const char* pCStrKey = pKey.c_str();
//第一次调用返回转换后的字符串长度,用于确认为wchar_t*开辟多大的内存空间
int pSize = MultiByteToWideChar(CP_OEMCP, 0, pCStrKey, strlen(pCStrKey) + 1, NULL, 0);
wchar_t* pWCStrKey = new wchar_t[pSize];
//第二次调用将单字节字符串转换成双字节字符串
MultiByteToWideChar(CP_OEMCP, 0, pCStrKey, strlen(pCStrKey) + 1, pWCStrKey, pSize);
return pWCStrKey;
}
int main()
{
std::cout << "\n";
Book* book = xlCreateBook();
if (book)
{
//注册
//book->setKey(L"TommoT", L"windows-2421220b07c2e10a6eb96768a2p7r6gc");
//book->setKey(L"Halil Kural", L"windows-2723210a07c4e90162b26966a8jcdboe");
bool result = book->load(L"levelTxt.xlsx");
if (result)
{
Sheet* sheet = book->getSheet(0);
double num = sheet->readNum(4, 0); //读取第5行第1列的数值
const wchar_t* chars = sheet->readStr(4, 5);//读取第5行第6列的字符串
string str;
WcharToString(str, chars);
std::cout << num <<"\n";
std::cout << str <<"\n";
num += 1;
str += "(copy)";
wchar_t* wchar = StringToWchar(str);
sheet->writeNum(4, 0, num);
sheet->writeStr(4, 5, wchar);
//好恶心啊
delete[]wchar;
}
else
{
std::cout << book->errorMessage() << std::endl;
}
/*Sheet* sheet = book->addSheet(L"Sheet1");
if (sheet)
{
sheet->writeStr(2, 1, L"Hello, World !");
sheet->writeNum(4, 1, 1000);
sheet->writeNum(5, 1, 2000);
}
*/
if (book->save(L"levelTxt.xlsx") == false)
{
std::cout <<"save failed: " << book->errorMessage() << std::endl;
}
book->release();
}
std::cout << "\n";
}
注意事项:
1.自己创建的excel表可能会有格式无效问题,可以直接代码创建一张表再进行修改
2.体验版第一行会有需要购买或**
3.save failed可能是你的表开着的