DPS/DataPlatform/ExcelOP.cpp

121 lines
2.6 KiB
C++
Raw Normal View History

2025-06-23 10:41:33 +08:00
#pragma execution_character_set("utf-8")
#include "ExcelOP.h"
#include "common.h"
#include "easylogging++.h"
//xlntʹ<74><CAB9>utf8
ExcelOP::ExcelOP()
{
}
ExcelOP::~ExcelOP()
{
}
bool ExcelOP::OpenFile(QString& filePath)
{
try
{
wb.load(CommonHelper::qstringToUtf8(filePath));
}
catch (std::exception const& e)
{
LOG(INFO) << "OpenFile exception";
LOG(ERROR) << CommonHelper::utf8ToString(e.what());
return false;
}
return true;
}
void ExcelOP::saveFile(QString& filePath)
{
try
{
wb.save(CommonHelper::qstringToUtf8(filePath));
}
catch (std::exception const& e)
{
LOG(INFO) << "saveFile exception";
LOG(INFO) << CommonHelper::utf8ToString(e.what());
CommonHelper::message("<EFBFBD><EFBFBD>ļ<EFBFBD>ʧ<EFBFBD><EFBFBD>", 2);
}
}
bool ExcelOP::readSheetData(QString name, QList<QStringList>& result, bool& hasEmptyCell)
{
using namespace std;
hasEmptyCell = false;
try
{
if (!wb.contains(CommonHelper::qstringToUtf8(name)))
{
//û<>и<EFBFBD>sheetҳ,<2C><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
QString msg = "ExcelOP::readSheetData<74><61>û<EFBFBD>и<EFBFBD>sheetҳ " + name;
LOG(ERROR) << CommonHelper::qstringToString(msg);
return false;
}
vector<string> t = wb.sheet_titles();
auto ws = wb.sheet_by_title(CommonHelper::qstringToUtf8(name));
auto rows = ws.rows();
auto cols = ws.columns();
int rowLen = static_cast<int>( rows.length());
int colLen = static_cast<int>(cols.length());
cols[0][0].value<std::string>();
for (int row = 0; row < rowLen; row++)
{
if (rows[row][0].to_string() == "")
{
continue;
}
QStringList slist;
for (int col = 0; col < colLen; col++)
{
if (rows[row][col].to_string() == "")
{
hasEmptyCell = true;
slist.append(" ");
}
else {
slist.append(CommonHelper::utf8ToQString(rows[row][col].to_string()));
}
}
result.append(slist);
}
}
catch (xlnt::exception const& e)
{
LOG(INFO) << "readSheetData exception";
LOG(ERROR) << CommonHelper::utf8ToString(e.what());
return false;
}
return true;
}
//дָ<D0B4><D6B8>sheetҳ<74><D2B3><EFBFBD>ݣ<EFBFBD>û<EFBFBD><C3BB>sheetҳ<74><D2B3><EFBFBD>½<EFBFBD>
void ExcelOP::writeSheetData(QString name, QList<QStringList>& input)
{
currentSheet = wb.create_sheet();
currentSheet.title(CommonHelper::qstringToUtf8(name));
for (int i = 0; i < input.size(); i++)
{
QStringList rowValue = input[i];
for (int col = 0; col < rowValue.size(); col++)
{
currentSheet.cell(col + 1, i + 1).value(CommonHelper::qstringToUtf8(rowValue.at(col)));
}
}
}
void ExcelOP::clearAllSheet()
{
using namespace std;
vector<string> titles = wb.sheet_titles();
xlnt::worksheet wh;
int id = 1;
for (auto i : titles)
{
xlnt::worksheet sh = wb.sheet_by_id(id);
wb.remove_sheet(sh);
id++;
}
}