如何从Excel获取Unicode字符串

how to get unicode string from excel

本文关键字:Unicode 字符串 获取 Excel      更新时间:2023-10-16

嗨,我正在使用Excel格式库从包含一些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 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 字符正确复制 excel 文件,但在将数据保存到新文件之前,我需要对它进行一些操作,如果字符串不是 Unicode,我可以使用它

sheet->Cell(y, x)->GetString();

它工作正常,但是当我有Unicode数据时,即使使用

sheet->Cell(y, x)->GetWString();

因为它返回一些数字,而我无法使用它,我应该如何将 GetWstring 的结果转换为适当的文本格式

cout << sheet->Cell(y, x)->GetWString();

GetWString返回wchar_t* . cout不知道该怎么办 - 你应该改用wcout

从我能找到的最接近 API 的东西:

const wchar_t* GetWString() const   Get an Unicode string. Returns 0 if cell 
                                    does not contain an Unicode string.

来自文章:

http://www.codeproject.com/Articles/13852/BasicExcel-A-Class-to-Read-and-Write-to-Microsoft

在挖掘了一些其他库后,我发现libxl很好并且与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