C++ 如何从excel中获取unicode字符串
您好,我正在使用ExcelFormat库从包含一些unicode字符的excel文件(.xls)中提取一些内容。下面是代码C++ 如何从excel中获取unicode字符串,c++,excel,visual-c++,unicode,C++,Excel,Visual C++,Unicode,您好,我正在使用ExcelFormat库从包含一些unicode字符的excel文件(.xls)中提取一些内容。下面是代码 BasicExcel xls(from); XLSFormatManager fmt_mgr(xls); BasicExcelWorksheet* sheet = xls.GetWorksheet(0); CellFormat fmt_general(fmt_mgr); fmt_general.set_format_string("0.000"); for (int
BasicExcel xls(from);
XLSFormatManager fmt_mgr(xls);
BasicExcelWorksheet* sheet = xls.GetWorksheet(0);
CellFormat fmt_general(fmt_mgr);
fmt_general.set_format_string("0.000");
for (int y = 0; y<2; ++y) {
for (int x = 0; x<2; ++x) {
BasicExcelCell* cell = sheet->Cell(y, x);
cout << sheet->Cell(y, x)->GetWString();
CellFormat fmt(fmt_mgr, cell);
const Workbook::Font& font = fmt_mgr.get_font(fmt);
string font_name = stringFromSmallString(font.name_);
const wstring& fmt_string = fmt.get_format_string();
cell->SetFormat(fmt_general);
cout << endl;
}
}
cout << "write: " << from << endl;
xls.SaveAs(to);
它工作得很好,但是当我有unicode数据时,即使使用unicode,我也无法读取它
sheet->Cell(y, x)->GetWString();
因为它返回一些数字,而我无法使用它,所以我应该如何将GetWstring的结果转换为适当的文本格式cout Cell(y,x)->GetWstring();
cout << sheet->Cell(y, x)->GetWString();
GetWString
返回wchar\u t*
cout
不知道该怎么办-您应该改用wcout
。从我能找到的最接近API的东西:
const wchar_t* GetWString() const Get an Unicode string. Returns 0 if cell
does not contain an Unicode string.
从文章中:
在挖掘了一些其他库之后,我发现了一个与unicode和其他语言兼容的很好的库,在您下载的包中有一些很好的示例,如果您是这个库的新手,我建议您在libxl中使用如下基本代码
#include "libxl.h"
using namespace libxl;
int main()
{
Book* book = xlCreateBook(); // xlCreateXMLBook() for xlsx
if(book)
{
Sheet* sheet = book->addSheet(L"Sheet1");
if(sheet)
{
sheet->writeStr(2, 1, L"Hello, World !");
sheet->writeNum(3, 1, 1000);
}
book->save(L"example.xls");
book->release();
}
}
但是这个库不是免费的,我想你可以解析100个单元格或行,但不能解析更多。它适用于linux windows和mac我知道我不应该使用cout,但当我使用wcout时,我会遇到访问冲突的异常,通过适当的文本格式,我的意思是按excel中的格式打印字符串file@ZiDoM如果我没记错的话根据项目设置和与
cout
的混合,wcout
可能会出现一些问题。我相信wprintf()
混合效果更好。@ZiDoM您是否检查了NULL
ie:0
从GetWString()
返回?否则,根据规范,它应该是一个有效的wchar\u t*
。@ebyrob是的,它的值为null,但当我在excel文件中放入一些英文文本时,它不应该为null,一切正常,但当unicode出现时,它返回null。请尝试将结果放入一个变量:wchar\u t*foo=sheet->Cell(y,x)->GetWString()代码>然后看看你在那里找到了什么。在某些索引中,应该有16位字符(例如:0065)。希望调试器甚至能显示字符串内容。@ebyrob这仍然会给出错误存储返回变量怎么会导致错误?这是编译错误还是运行时错误?您遇到了什么错误?似乎返回了unicode字符。谢谢您的帮助,我认为这个库不支持阿拉伯语或波斯语
#include "libxl.h"
using namespace libxl;
int main()
{
Book* book = xlCreateBook(); // xlCreateXMLBook() for xlsx
if(book)
{
Sheet* sheet = book->addSheet(L"Sheet1");
if(sheet)
{
sheet->writeStr(2, 1, L"Hello, World !");
sheet->writeNum(3, 1, 1000);
}
book->save(L"example.xls");
book->release();
}
}