Error with the formulas - phpexcel

I want to set formula to cell but im getting error on my way. Theres a code:
$objReader = PHPExcel_IOFactory::load($path.$filename);
$objReader->setActiveSheetIndex(0);
$objReader->getActiveSheet()
->setCellValue('C2','=VLOOKUP(A9;A3:B32;2)');
$objWriter = PHPExcel_IOFactory::createWriter($objReader, 'Excel5');
$objWriter->save($path.'plik.xls');
Formula is copied from normal sheet so she's wright. Im getting this msg: feuil1!C2 -> Formula Error: An unexpected error occured.

Unless you've enabled a locale that uses ; as an argument separator, then you must use an English (en_us) argument separator (ie, a comma ,)
Quoting from the manual:
Inside the Excel file, formulas are always stored as they would appear in an English version of Microsoft Office Excel, and PHPExcel handles all formulae internally in this format. This means that the following rules hold:
• Decimal separator is '.' (period)
• Function argument separator is ',' (comma)
• Matrix row separator is ';' (semicolon)
• English function names must be used
This is regardless of which language version of Microsoft Office Excel may have been used to create the Excel file.
so:
$objReader = PHPExcel_IOFactory::load($path.$filename);
$objReader->setActiveSheetIndex(0);
$objReader->getActiveSheet()
->setCellValue('C2','=VLOOKUP(A9,A3:B32,2)');
$objWriter = PHPExcel_IOFactory::createWriter($objReader, 'Excel5');
$objWriter->save($path.'plik.xls');
EDIT
If you want to use French language formulae, then you need to enable the locale, and convert the formulae between French and English:
$objReader = PHPExcel_IOFactory::load($path.$filename);
$objReader->setActiveSheetIndex(0);
$locale = 'fr';
$validLocale = PHPExcel_Settings::setLocale($locale);
if (!$validLocale) {
echo 'Unable to set locale to '.$locale." - reverting to en_us<br />\n";
$internalFormula = '=VLOOKUP(A9,A3:B32,2)';
} else {
$formula = '=RECHERCHEV(A9;A3:B32;2)';
$internalFormula =
PHPExcel_Calculation::getInstance()->translateFormulaToEnglish($formula);
}
$objReader->getActiveSheet()
->setCellValue('C2', $internalFormula);
$objWriter = PHPExcel_IOFactory::createWriter($objReader, 'Excel5');
$objWriter->save($path.'plik.xls');

Related

Workaround for case-sensitive input to dir

I am using Octave 5.1.0 on Windows 10 (x64). I am parsing a series of directories looking for an Excel spreadsheet in each directory with "logbook" in its filename. The problem is these files are created by hand and the filenaming isn't consistent: sometimes it's "LogBook", other times it's "logbook", etc...
It looks like the string passed as input to the dir function is case-sensitive so if I don't have the correct case, dir returns an empty struct. Currently, I am using the following workaround, but I wondered if there was a better way of doing this (for a start I haven't captured all possible upper/lower case combinations):
logbook = dir('*LogBook.xls*');
if isempty(logbook)
logbook = dir('*logbook.xls*');
if isempty(logbook)
logbook = dir('*Logbook.xls*');
if isempty(logbook)
logbook = dir('*logBook.xls*');
if isempty(logbook)
error(['Could not find logbook spreadsheet in ' dir_name '.'])
end
end
end
end
You need to get the list of filenames (either via readdir, dir, ls), and then search for the string in that list. If you use readdir, it can be done like this:
[files, err, msg] = readdir ('.'); # read current directory
if (err != 0)
error ("failed to readdir (error code %d): %s", msg);
endif
logbook_indices = find (cellfun (#any, regexpi (files, 'logbook'));
logbook_filenames = files(logbook_indices);
A much less standard approach could be:
glob ('*[lL][oO][gG][bB][oO][kK]*')

Test Regex with new line string \n via PHPUnit

I created a php library that parse content via regex. One of this regex is '#\n-{3,}#' to parse --- only with an break, a new line, before.
I have also tests written in PHPUnit for all methods and always I get a failure for tests with the new line regex. I test always with assertSame()
I tried to set as input the follow strings:
$input = PHP_EOL . '---';
$input = '<br>---';
$input = '
---'; // with break in code
As expected I set:
'<hr/>'
However always it fail and get an error. If I send this variables to the assert check it will fail and parse not the new line. Only without the \n inside the Regex, like '#-{3,}#', it works fine without error for the tests.
Also if I use as input for the test a new line with a string before, it works also, like
$input = "test\n---";
But I would like also to test without string, only start with a new line.
The parse for front end works fine, it replace via this regex from my markdown file if the content is include a break and followed by the 3 -.
How is it possible to set as input for the assertSame() function in PHPUnit a new line before the string?
The problem is you are using single quotes in your pattern.
In PHP \n means "new line" in a string only if double quotes are used.
$input = PHP_EOL . '---';
preg_match("#\n-{3,}#", $input); // this will match
See https://3v4l.org/EpEGf

python creation json with plone object

I've a json file with plone objects and there is one field of the objects giving me an error:
UnicodeDecodeError('ascii', '{"id":"aluminio-prata", "nome":"ALUM\xc3\x8dNIO PRATA", "num_demaos":0, "rendimento": 0.0, "unidade":"litros", "url":"", "particular":[], "profissional":[], "unidades":[]},', 36, 37, 'ordinal not in range(128)') (Also, the following error occurred while attempting to render the standard error message, please see the event log for full details: 'NoneType' object has no attribute 'getMethodAliases')
I already know witch field is, is the "title" from title = obj.pretty_title_or_id(), when I remove it from here its ok:
json += '{"id":"' + str(id) + '", "nome":"' + title + '", "num_demaos":' + str(num_demaos) + ', "rendimento": ' + str(rendimento) + ', "unidade":"' + str(unidade) + '", "url":"' + link_produto + '", "particular":' + arr_area_particular + ', "profissional":' + arr_area_profissional + ', "unidades":' + json_qtd + '},
but when I leave it I've got this error.
UnicodeDecodeError('ascii', '{"id":"aluminio-prata", "nome":"ALUM\xc3\x8dNIO PRATA", "num_demaos":0, "rendimento": 0.0, "unidade":"litros", "url":"", "particular":[], "profissional":[], "unidades":[]},', 36, 37, 'ordinal not in range(128)') (Also, the following error occurred while attempting to render the standard error message, please see the event log for full details: 'NoneType' object has no attribute 'getMethodAliases')
I'm going to assume that the error occurs when you're reading the JSON file.
Internally, Plone uses Python Unicode strings for nearly everything. If you read a string from a file, it will need to be decoded into Unicode before Plone can use it. If you give no instructions otherwise, Python will assume that the string was encoded as ASCII, and will attempt its Unicode conversion on that basis. It would be similar to writing:
unicode("ALUM\xc3\x8dNIO PRATA")
which will produce the same kind of error.
In fact, the string you're using was evidently encoded with the UTF-8 character set. That's evident from the "\xc3", and it also makes sense, because that's the character set Plone uses when it sends data to the outside world.
So, how do you fix this? You have to specify the character set that you wish to use when you convert to Unicode:
"ALUM\xc3\x8dNIO PRATA".decode('UTF8')
This gives you a Python Unicode string with no error.
So, after you've read your JSON file into a string (let's call it mystring), you will need to explicitly decode it by using mystring.decode('UTF8'). unicode(mystring, 'UTF8') is another form of the same operation.
As Steve already wrote do title.decode('utf8')
An Example illustrate the facts:
>>> u"Ä" == u"\xc4"
True # the native unicode char and escaped versions are the same
>>> "Ä" == u"\xc4"
False # the native unicode char is '\xc3\x84' in latin1
>>> "Ä".decode('utf8') == u"\xc4"
True # one can decode the string to get unicode
>>> "Ä" == "\xc4"
False # the native character and the escaped string are
# of course not equal ('\xc3\x84' != '\xc4').
I find this Thread very helpfull for Problems and Understanding with Encode/Decode of UTF-8.

CSV file (with special characters) upload encoding issue

I am trying to upload a CSV file that has special characters using ServletFileUpload of apache common. But the special characters present in the CSV are being stored as junk characters in the database. The special characters I have are Trademark, registered etc. Following is the code snippet.
ServletFileUpload upload = new ServletFileUpload();
FileItemIterator iter = upload.getItemIterator(request);
while (iter.hasNext()) {
FileItemStream item = iter.next();
String name = item.getFieldName();
InputStream stream = item.openStream();
if (item.isFormField()) {
System.out.println("Form field " + name + " with value "
+ Streams.asString(stream, "UTF-8") + " detected.");
}
}
I have tried reading it using BufferendReader, used request.setCharacterEncoding("UTF-8"), tried upload.setHeaderEncoding("UTF-8") and also checked with IOUtils.copy() method, but none of them worked.
Please advice how to get rid of this issue and where it needs to be addressed? Is there anything I need to do beyond servlet code?
Thanks
What database are using? What character set is database using? Characters can be malformed in the database rather than in Java code.

QRegExp: individual quantifiers can't be non-greedy, but what good alternatives then?

I'm trying to write code that appends ending _my_ending to the filename, and does not change file extension.
Examples of what I need to get:
"test.bmp" -> "test_my_ending.bmp"
"test.foo.bar.bmp" -> "test.foo.bar_my_ending.bmp"
"test" -> "test_my_ending"
I have some experience in PCRE, and that's trivial task using it. Because of the lack of experience in Qt, initially I wrote the following code:
QString new_string = old_string.replace(
QRegExp("^(.+?)(\\.[^.]+)?$"),
"\\1_my_ending\\2"
);
This code does not work (no match at all), and then I found in the docs that
Non-greedy matching cannot be applied to individual quantifiers, but can be applied to all the quantifiers in the pattern
As you see, in my regexp I tried to reduce greediness of the first quantifier + by adding ? after it. This isn't supported in QRegExp.
This is really disappointing for me, and so, I have to write the following ugly but working code:
//-- write regexp that matches only filenames with extension
QRegExp r = QRegExp("^(.+)(\\.[^.]+)$");
r.setMinimal(true);
QString new_string;
if (old_string.contains(r)){
//-- filename contains extension, so, insert ending just before it
new_string = old_string.replace(r, "\\1_my_ending\\2");
} else {
//-- filename does not contain extension, so, just append ending
new_string = old_string + time_add;
}
But is there some better solution? I like Qt, but some things that I see in it seem to be discouraging.
How about using QFileInfo? This is shorter than your 'ugly' code:
QFileInfo fi(old_string);
QString new_string = fi.completeBaseName() + "_my_ending"
+ (fi.suffix().isEmpty() ? "" : ".") + fi.suffix();

Resources