tfussell / xlnt

:bar_chart: Cross-platform user-friendly xlsx library for C++11+
Other
1.47k stars 409 forks source link

cell is date type , but read out is wrong #641

Open liufeijin opened 2 years ago

liufeijin commented 2 years ago

The excel file cell is
image use qt to read out it by QString::fromStdString(ws.cell("B13").to_string())

but got string "44733", how can i to get correct date from excel cell.

sbj42 commented 2 years ago

This may be a bug. cell.to_string() uses cell.computed_number_format() to format the value, but cell.computed_number_format() is currently implemented to always return the default "Generic" format.

So the cell's number_format is a date, but since computed_number_format is basically unimplemented, to_string will always return a generic formatting of the value.

Looks like a possible workaround right now is:

std::string str;
if (cell.has_format() && (cell.data_type() == xlnt::cell::type::date || cell.data_type() == xlnt::cell::type::number)) {
  auto nf = cell.number_format();
  str = nf.format(cell.value<double>(), workbook.base_date());
} else {
  str = cell.to_string();
}
derreisende77 commented 1 year ago

I am having similar problems reading dates from excel. Your workaround does return a readable result, but it is wrong: dd.mm.yyyy --> value<double>() --> workaround string result 01.01.1995 --> 34700 --> 01-01-995 01.10.1994 --> 34608 --> 10-01-994 01.10.2002 --> 37530 --> 10-01-02 31.12.9999 --> 2.95847e+06 -->12-31-999

Is there a way to fix it? Unfortunately I have to read those columns as date as they are generated externally from another program :(

derreisende77 commented 1 year ago

Okay I found a fix for me. Based on this SO thread I use the provided ExcelSerialDateToDMYfunction to convert cell.value() result into the correct day,month,year ints for further usage in my app.