1. 程式人生 > 其它 >使用xlnt庫讀取excel中文亂碼

使用xlnt庫讀取excel中文亂碼

技術標籤:windows程式設計

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;
}

編譯執行,即可發現亂碼問題解決了: