Autofilter PHPExcel - filter

I have an excel file who contains filter in a row.
I convert my excel file to HTML Table like that :
$excel = glob(''.$path'.{xlsx,xls,xlsm,xlsm.ink}', GLOB_BRACE);
$filterSubset = new \PHPExcel_Reader_DefaultReadFilter('A','N');
$objReader = \PHPExcel_IOFactory::createReaderForFile($excel[0]);
$objReader->setReadFilter($filterSubset);
/** Read the list of worksheet names and select the one that we want to load **/
$worksheetList = $objReader->listWorksheetNames($excel[0]);
$sheetname = $worksheetList[0];
/** Advise the Reader of which WorkSheets we want to load **/
$objReader->setLoadSheetsOnly($sheetname);
/** Load $inputFileName to a PHPExcel Object **/
$objPHPExcel = $objReader->load($excel[0]);
### HERE I DONT KNOW WHAT TO DO ###
$autoFilter = $objPHPExcel->getActiveSheet()->getAutoFilter();
$autoFilter->showHideRows();
var_dump($autoFilter);
$objPHPExcel->getActiveSheet()->setAutoFilter('A1:N1');
### HELP ME PLEASE ###
$writer = \PHPExcel_IOFactory::createWriter($objPHPExcel, "HTML");
$writer->generateStyles();
$writer->generateSheetData();
I just wanna know how to apply and display my filters. range('A1:N1') .
Thanks for help

When you set Autofilter, you need to set the full range of data, not simply the headers; but Autofilter is only provided for native Excel formats only, and not available for HTML

Related

Google sheets script Exceeded maximum execution time

I wrote a script to import stock data from a csv file stored in Google Drive to an existing google sheet.
In one function I'm doing this for multiple csv files. Unfortunately I get "Exceeded maximum execution time" sometimes, but not all the time.
Do you have an idea how I can boost performance on this:
//++++++++++++++ SPY +++++++++++++++++++
var file = DriveApp.getFilesByName("SPY.csv").next();
var csvData = Utilities.parseCsv(file.getBlob().getDataAsString());
//Create new temporary sheet
var activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var yourNewSheet = activeSpreadsheet.getSheetByName("SPY-Import");
if (yourNewSheet != null) {
activeSpreadsheet.deleteSheet(yourNewSheet);
}
yourNewSheet = activeSpreadsheet.insertSheet();
yourNewSheet.setName("SPY-Import");
//Import
var sheet = SpreadsheetApp.getActiveSheet();
sheet.getRange(1, 1, csvData.length, csvData[0].length).setValues(csvData);
//Copy from temporary sheet to destination
var spreadsheet = SpreadsheetApp.getActive();
spreadsheet.getRange('A:B').activate();
spreadsheet.setActiveSheet(spreadsheet.getSheetByName('SPY'), true);
spreadsheet.getRange('A2').activate();
spreadsheet.getRange('\'SPY-Import\'!A:B').copyTo(spreadsheet.getActiveRange(),
SpreadsheetApp.CopyPasteType.PASTE_NORMAL, false);
//Delete temporary sheet
// Get Spreadsheet Object
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
// Get target sheet object
var sheet = spreadsheet.getSheetByName("SPY-Import");
// Delete
spreadsheet.deleteSheet(sheet);
Thanks in advance!
I believe your situation and goal as follows.
You have several CSV files like SPY.csv.
Your Spreadsheet has the several sheet corresponding to each CSV file like SPY.
You want to put the values from the CSV data to the Spreadsheet.
You want to put the values of the column "A" and "B" of the CSV data.
In your current situation, you copied the script in your question several times and run them by changing the csv filename and sheet name.
You want to reduce the process cost of your script. I understood your goal like this.
Modification points:
SpreadsheetApp.getActiveSpreadsheet() is used several times. And, activate() is used several times.
I think that in your case, SpreadsheetApp.getActiveSpreadsheet() can be declared one time, and activate() is not required to be used.
In order to copy the CSV data to Spreadsheet, the CSV data is put to a temporal sheet and the required values are copied to the destination sheet.
In this case, I think that the CSV data is directly put to the destination sheet by processing on the array.
I think that above points lead to the reduction of process cost. When above points are reflected to your script, it becomes as follows.
Modified script:
Please copy and paste the following script and prepare the variable of obj. When you run the script, the CSV data is retrieved and processed, and then, the values are put to the Spreadsheet.
function myFunction() {
var obj = [
{filename: "SPY.csv", sheetname: "SPY"},
{filename: "###.csv", sheetname: "###"},
,
,
,
];
var ss = SpreadsheetApp.getActiveSpreadsheet();
obj.forEach(({filename, sheetname}) => {
var file = DriveApp.getFilesByName(filename);
if (file.hasNext()) {
var sheet = ss.getSheetByName(sheetname);
if (sheet) {
// sheet.clearContents(); // Is this requierd in your situation?
var csv = DriveApp.getFileById(file.next().getId()).getBlob().getDataAsString();
var values = Utilities.parseCsv(csv).map(([a, b]) => [a, b]);
sheet.getRange(2, 1, values.length, 2).setValues(values);
}
}
});
}
Note:
Please use this script with enabling V8
I'm not sure about your CSV data. So when Utilities.parseCsv(csv) cannot be used, please use the delimiter.
In this modification, Spreadsheet service is used. If above modified script occurs the same error of Exceeded maximum execution time, please tell me. At that time, I would like to propose the sample script using Sheets API.
References:
Spreadsheet Service
parseCsv(csv)

How to convert a json to a a proper table in Power Query

I created a Power BI Custom Data Connector, the idea is to be able to connect to SSRS Dataset using this Custom Data Connector I was able to do it but the resulting formatted json is different from what i expect.
Here's the result when I open the Custom Connector in Power BI, I expected a properly formatted table but the result is not.
Columns are List of Record contain the Column Names and Type
While the Row is a List of List containing the values for CustomerID and CustomerName.
Here's my code.
section Test.PQ.SSRS_Connector;
[DataSource.Kind="Asia.PQ.SSRS_Connector", Publish="Test.PQ.SSRS_Connector.Publish"]
shared Test.PQ.SSRS_Connector.Feed = Value.ReplaceType(SSRSConImpl, type function (url as Uri.Type) as any);
DefaultRequestHeaders = [
#"Accept" = "application/json;odata.metadata=minimal",
#"OData-MaxVersion" = "4.0"
];
SSRSConImpl = (url as text) =>
let
body= "",
source = Web.Contents(url, [ Headers = DefaultRequestHeaders, Content=Text.ToBinary(body)]),
json = Json.Document(source)
in
json;
Posting some sample JSON would be helpful, but based on the screenshots it seems like continuing your function as below may work:
// ... Your function code
json = Json.Document(source),
toTable = Table.FromRows(json[Rows], {"CustomerID", "CustomerName"}) // If there are more columns, consider extracting names dynamically from json[Columns]
// .... Any remaining code
Code is untested.

Programmatically adding default image to content type

Is there a way to add a "default image" file to a content type field, using features, a module or anything. The only way I have found so far is adding the image link to each node created without an image, but I was wondering if I could use something better and recommended
I found some related info here question.
-- EDIT --
To clarify, I do mean "a default image for a image field in a content type"
BUT, I am creating the content type using features and a the site using a script. I cannot use the form or anything related as I will potentially NEVER touch the site myself. I want to automate it all (:
Thanks!
Default images won't come across in features, but you can use hook_field_default_fields_alter in a module to set the default image for that field.
Here's a discussion on it on the Drupal site:
https://drupal.org/node/1439136
comment 6 is a single use case which you could adapt for your field, while comment 7 is a more general solution which you can use for several fields.
I have been meaning to try something similar. Not sure exactly how it will work but the genral idea is as follows:
Create a rule - on insert of the content Type.
Have the rule set a data value which will be the image.
In my case I intend creating a new content type (ImageNodes) that will simply be a small, static set of nodes. Each ImageNodes node will consist of a key and an image. When setting the data value in my rule I will inspect another field in the content being inserted and use that as a reference to the correct ImageNodes node.
This approach will allow me to attach default images to my content nodes on insert, to allow it to attach alternate images based on the contents of the inserted node.
Note, this approach can be implemented with the image being created as an entity reference (or similar), or alternatively the rules module is smart enough that I can copy the image field in the ImageNodes node to an image field in the content node being inserted. Adding a condition to the rule will give you the ability to only inject the default image if none has been selected.
The following code I adapted from Features issue #1439136: Support imagefield default images on drupal.org to work with Features API version 1.
It can easily be adapted though to work with Features API version 2 by changing the hook name as described in the notes and comments below.
This code sample should be added to your main module file modulename.module. I would suggest it is best to add to the features module where the entity and fields are defined. It should work with any Drupal fieldable entities. I've used it with users, nodes, taxonomy vocabularies, and field collection items.
To implement this in your own module, copy the code below and then:
Replace all occurrences of modulename with your module machine name.
Define all your field image defaults in the array returned by modulename_images_fields_defaults().
Place your default images into your module path using a folder named images.
Notes:
Field machine names can easily be located and copied from the Features API 1 file named modulename.features.field.inc.
In Features API 2 the fields definition is split into modulename.features.field_bases.inc and modulename.features.field_instances.inc, so the hook also is renamed and can be used for either the field base or field instance:
hook_field_default_field_bases_alter()
hook_field_default_field_instances_alter()
Code:
<?php
/**
* Define images for use as defaults in fields info.
*
* #return array
*/
function modulename_images_fields_defaults() {
return array(
'node-content_type_name-field_image' => 'default-image.png',
'field_collection_item-field_collection_item_field_name-field_image' => 'default-image.png',
'taxonomy_term-vocabulary_name-field_image' => 'default-image.png',
);
}
/**
* Implements hook_field_default_fields_alter().
*
* Alter field default values right before fields info is cached by features.
*
* #todo: Update to hook_field_default_field_bases_alter if Features upgraded.
*
* #param &$fields
* By reference. The fields that have been declared by another feature.
*/
function modulename_field_default_fields_alter(&$fields) {
$source = drupal_get_path('module', 'modulename') . '/images';
$destination = file_default_scheme() . '://default_images';
$field_default_images = modulename_images_fields_defaults();
foreach ($field_default_images as $field_name => $filename) {
if (isset($fields[$field_name])) {
_modulename_field_default_fields_alter_image(
$fields[$field_name], $filename, $source, $destination
);
}
}
}
/**
* Alter image field default using managed source file.
*
* #param $field
* #param $filename
* #param $source_path
* The source folder path relative to the Drupal root where the image
* filename can be found.
* #param $destination_uri
* The destination folder path as a stream wrapper uri ie. "scheme://target".
*/
function _modulename_field_default_fields_alter_image(&$field, $filename, $source_path, $destination_uri) {
// See if a default image hasn't been set for this field yet
if (!isset($field['field_config']['settings']['default_image'])
|| empty($field['field_config']['settings']['default_image'])
) {
// Dynamically set the default image on the field
$source_file_uri = "$source_path/$filename";
// Check to see if managed file exists.
$result = db_select('file_managed', 'f')
->fields('f', array('fid'))
->condition('f.uri', "$destination_uri/$filename")
->execute();
$fid = $result->fetchField();
// Simulate an upload of the default image.
if (!$fid && file_exists($source_file_uri)) {
$file = new stdClass;
$file->filename = $filename;
$file->timestamp = REQUEST_TIME;
$file->uri = $source_file_uri;
$file->filemime = file_get_mimetype($source_file_uri);
$file->uid = 1;
$file->status = 1;
$file = file_copy($file, $destination_uri, FILE_EXISTS_REPLACE);
$fid = isset($file->fid) ? $file->fid : '';
}
$scheme = file_uri_scheme($destination_uri) ?: file_default_scheme();
$field['field_config']['settings']['default_image'] = intval($fid);
$field['field_config']['settings']['uri_scheme'] = $scheme;
}
}

Getting the last insert of your table

I have a table RECEIPT and the ID that i created is
REC-201290001 = "REC-"+"YEAR"+"MONTH"+"0001"
I create the number with a String.Format but in order to create the next one i need the last ID i inserted so i can increase it.
Thanks very much for your help.
$query = mysql_query("select value from config where name = 'next_receipt_id'");
$row = mysql_fetch_assoc($query);
$receiptId = "REC-"+"YEAR"+"MONTH"+$row['value'];
$insert_query = mysql_query("INSERT into order (`id`,...) values($receiptId,...)");
$updateReceiptId = mysql_query("update config set value = value+1 where name = 'next_receipt_id');
You need some kind of persistent storage for a counter. You generate fresh IDs using that counter as a seed.
You can use a simple file, or, more elegant, a database for the purpose of the persistent storage. There are hundreds of tutorials in the internet about this.

Get id of last created album in Picasa (gdata) PHP

Im trying to insert a photo on a newly created album. But i couldnt find a way on how to get the last generated Album ID.
$entry = new Zend_Gdata_Photos_AlbumEntry();
$entry->setTitle($gp->newTitle("Test album"));
$entry->setSummary($gp->newSummary("This is an album."));
$createdEntry = $gp->insertAlbumEntry($entry);
From the example on gdata:
$username = "default";
$filename = "C:/xampp/htdocs/test.jpg";
$photoName = "My Test Photo";
$albumId = "5626728515640093041";
:
:
// We use the AlbumQuery class to generate the URL for the album
$albumQuery = $gp->newAlbumQuery();
$albumQuery->setUser($username);
$albumQuery->setAlbumId($albumId);
$insertedEntry = $gp->insertPhotoEntry($photoEntry, $albumQuery->getQueryUrl());
How can I know the last inserted album without typing it manually?
Thanks so much!
Have a look on http://code.google.com/intl/zh-TW/apis/picasaweb/docs/2.0/developers_guide_protocol.html#AddAlbums
Picasa Web Albums creates a new album using the data you sent, then returns an HTTP 201 status code, along with a copy of the new album in the form of an "entry" element. The returned entry is similar to the one you sent, but the returned one contains various elements added by the server, such as an "id" element.
Therefore, you can get the albumID by parse the returned entry.
/* Use the AlbumQuery class to generate the URL for the album */
$albumQuery = $gp->newAlbumQuery();
$albumQuery->setUser($user);
$albumQuery->setAlbumName($albumName);
/* Insert the photo, and the server returns the entry representing the photo after it is uploaded */
$insertedEntry = $gp->insertPhotoEntry($photoEntry, $albumQuery->getQueryUrl());
$pialbum = $insertedEntry->getGphotoAlbumId()->getText();
$pifoto = $insertedEntry->getGphotoId()->getText();

Resources