Files
baidu_fanyi/bf.xlnt.cpp
2026-03-10 14:32:11 +08:00

98 lines
2.9 KiB
C++

#include "bf.xlnt.h"
void BF_Xlnt::Reset()
{
fanyiHistory_.clear();
}
void BF_Xlnt::Set(BF_Interface* request, std::shared_ptr<BF_Config> bfConfig)
{
request_ = request;
bfConfig_ = bfConfig;
}
bool BF_Xlnt::parseXlsx(const std::string& file, std::vector<XlsxTask>& tasks, const std::string& sheetName)
{
xlnt::workbook wb;
xlnt::worksheet ws;
std::string out;
try {
wb.load(file);
ws = wb.sheet_by_title(sheetName);
for (auto& task : tasks) {
for (int i = task.startRow; i <= task.endRow; i++) {
for (int j = task.startCol; j <= task.endCol; j++) {
gLogger->debug("==================================================");
if (Fanyi(i, j, ws, task, out) && !fanyiHistory_.count(task.from)) {
fanyiHistory_[task.from] = out;
}
std::this_thread::sleep_for(std::chrono::milliseconds(bfConfig_->interval));
}
}
}
} catch (const std::exception& e) {
gLogger->error(e.what());
}
wb.save(fmt::format("{}_out.xlsx", file));
return true;
}
bool BF_Xlnt::Fanyi(int i, int j, xlnt::worksheet& ws, const XlsxTask& task, std::string& out)
{
xlnt::cell_reference cr;
if (!GetCell(i, j, ws, cr)) {
gLogger->error("获取数据失败:[{}][{}]", i, j);
return false;
}
xlnt::cell cell = ws.cell(cr);
std::string text = cell.value<std::string>();
BF_Util::trim(text);
if (text.empty()) {
gLogger->warn("数据为空,跳过:[{}][{}]", i, j);
return false;
}
if (fanyiHistory_.count(text)) {
out = fanyiHistory_[text];
gLogger->debug("使用历史数据结果:[{}][{}][{}]", i, j, text);
cell.value(out);
return true;
}
auto readyData = request_->doReady(text, task.from, task.to);
if (readyData.empty()) {
gLogger->warn("doReady数据为空,跳过:[{}][{}][{}]", i, j, text);
return false;
}
auto data = fmt::format("{}{}", bfConfig_->baseUrl, readyData);
std::string result = request_->getResult(data);
if (!BF_Request::HandleStr(result, out)) {
return false;
}
gLogger->info("翻译成功:[{}][{}][{}][{}]", i, j, text, out);
cell.value(out);
return true;
}
bool BF_Xlnt::GetCell(int i, int j, xlnt::worksheet& ws, xlnt::cell_reference& out)
{
try {
auto cell = ws.cell(j, i);
if (!cell.is_merged()) {
out = cell.reference();
return true;
}
bool isFind = false;
for (const auto& range : ws.merged_ranges()) {
if (range.contains(cell.reference())) {
out = range.top_left();
isFind = true;
break;
}
}
return isFind;
} catch (const std::exception& e) {
gLogger->error(e.what());
}
return false;
}