xlnt下载链接:https://github.com/tfussell/xlnt。基本操作介绍:《用XLNT库读写Excel文件》
一、问题描述:
如下图所示:存在excel文件“test.xlsx”,里面内容如下:
使用如下代码读取该excel文件中的内容:
#include <iostream>
#include <xlnt/xlnt.hpp>
using namespace std;
int main()
{
xlnt::workbook wb;
wb.load("test.xlsx");
auto ws = wb.active_sheet();
std::clog << "Processing spread sheet" << std::endl;
for (auto row : ws.rows(false))
{
for (auto cell : row)
{
std::clog << cell.to_string() << std::endl;
}
}
std::clog << "Processing complete" << std::endl;
return 0;
}
编译运行,结果发现打印出来的内容乱码:
二、解决方法:
将读取到的内容改变编码方式即可解决该问题。更改代码如下:
#include <iostream>
#include <xlnt/xlnt.hpp>
#include <Windows.h>
#include <wchar.h>
using namespace std;
//UTF-8编码格式字符串 转普通sting类型
std::string UTF8_To_string(const std::string & str)
{
int nwLen = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, NULL, 0);
wchar_t * pwBuf = new wchar_t[nwLen + 1];//一定要加1,不然会出现尾巴
memset(pwBuf, 0, nwLen * 2 + 2);
MultiByteToWideChar(CP_UTF8, 0, str.c_str(), str.length(), pwBuf, nwLen);
int nLen = WideCharToMultiByte(CP_ACP, 0, pwBuf, -1, NULL, NULL, NULL, NULL);
char * pBuf = new char[nLen + 1];
memset(pBuf, 0, nLen + 1);
WideCharToMultiByte(CP_ACP, 0, pwBuf, nwLen, pBuf, nLen, NULL, NULL);
std::string retStr = pBuf;
delete[]pBuf;
delete[]pwBuf;
pBuf = NULL;
pwBuf = NULL;
return retStr;
}
int main()
{
xlnt::workbook wb;
wb.load("test.xlsx");
auto ws = wb.active_sheet();
std::clog << "Processing spread sheet" << std::endl;
for (auto row : ws.rows(false))
{
for (auto cell : row)
{
//std::clog << cell.to_string() << std::endl;
string str1 = cell.to_string();
string str2 = UTF8_To_string(str1);
std::cout << str2 << std::endl;
}
}
std::clog << "Processing complete" << std::endl;
return 0;
}
编译运行,即可发现乱码问题解决了:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)