DPS/DataPlatform/ExcelOP.cpp

121 lines
2.6 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#pragma execution_character_set("utf-8")
#include "ExcelOP.h"
#include "common.h"
#include "easylogging++.h"
//xlnt使用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("存储文件失败", 2);
}
}
bool ExcelOP::readSheetData(QString name, QList<QStringList>& result, bool& hasEmptyCell)
{
using namespace std;
hasEmptyCell = false;
try
{
if (!wb.contains(CommonHelper::qstringToUtf8(name)))
{
//没有该sheet页,报错,返回
QString msg = "ExcelOP::readSheetData没有该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;
}
//写指定sheet页数据没有sheet页则新建
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++;
}
}