Windows excel转json工具实现 主要源文件
介绍主要的逻辑代码 一些简单的就没有展示了
//ExcelOperator.h 转sjon的主要类
//读取excel 分为每个sheet记录数据到类内
void ExcelOperator::ReadExcel(TSTR filePath)
{
xlnt::workbook wb;//xlnt 库
wb.load(filePath.c_str());
COUT << _T("sheet count:") << wb.sheet_count() << std::endl;
int sheetCount = wb.sheet_count();
ClearSheet();
for (int sheetIndex = 0; sheetIndex < sheetCount; ++sheetIndex)
{
auto ws = wb.sheet_by_index(sheetIndex);
xlnt::range range = ws.rows(false);
if (range[0][0].to_string().length() == 0)
continue;
TSTR title;
StrChangeT(ws.title(), title);
COUT << _T("sheet title : ") << title << std::endl;
//这里是分成了每个Sheet为一个记录对象
if (m_SheetMap.find(title) != m_SheetMap.end())
{
COUT << _T("error seam sheet title:") << title << std::endl;
continue;
}
SheetOperator* sheetOp = new SheetOperator();
m_SheetMap.insert(std::make_pair(title, sheetOp));
int rowIndex = 0;
//通过xlnt 获取excel数据 存入SheetOperator里
for (auto row : range)
{
++rowIndex;
sheetOp->m_ExcelData.insert(std::make_pair(rowIndex, std::map<int, TSTR>()));
int colIndex = 0;
if (row[0].to_string().length() != 0)
{
for (auto cell : row)
{
++colIndex;
TSTR tcell;
StrChangeT(cell.to_string(), tcell);
sheetOp->m_ExcelData[rowIndex].insert(std::make_pair(colIndex, tcell));
}
}
}
}
int pos = filePath.find_last_of(_T("\\"));
int pos2 = filePath.find_last_of(_T("."));
if (pos != TSTR::npos && pos2 != TSTR::npos)
{
m_ConfigName = filePath.substr(pos+1, pos2 - pos - 1);//文件名
}
else
{
m_ConfigName = _T("NotName");
}
m_OutPath = filePath.substr(0, pos);//默认的输出路径
}
//创建json文本的主函数
//根据加载的excel数据生成json字符串
void ExcelOperator::CreateConfig()
{
TSS context;
context << "{";
//遍历每个sheet
for (auto sheetIte = m_SheetMap.begin(); sheetIte != m_SheetMap.end(); ++sheetIte)
{
SheetOperator* pOp = sheetIte->second;
if (!pOp)
continue;
if (pOp->m_ExcelData.size() == 0)
{
COUT << _T("create config error not data ") << std::endl;
return;
}
auto fieldIte = pOp->m_ExcelData.find(DATAROW_FIELDTYPE);
if (fieldIte == pOp->m_ExcelData.end())
{
COUT << _T(" not find field type row") << std::endl;
return;
}
auto filedNameIte = pOp->m_ExcelData.find(DATAROW_USNAME);
if (filedNameIte == pOp->m_ExcelData.end())
{
COUT << _T(" not find field us name row") << std::endl;
return;
}
const std::map<int, TSTR> &fieldTypeMap = fieldIte->second;
const std::map<int, TSTR>& fieldNameMap = filedNameIte->second;
context << _T(&#