In Excel 2016 - Query Editor - Advanced Editor.
Here is my code:
let
SettingsSheet = Excel.CurrentWorkbook(){[Name="Table2"]}[Content],
#"TimeRange" = Table.TransformColumnTypes(SettingsSheet,{{"From", type datetime}, {"To", type datetime}}),
From = #"TimeRange"[From],
To = #"TimeRange"[To],
DateFormatString = "yyyy-MM-dd-THH:mm:ssZ",
FormattedFrom = DateTime.ToText(#"TimeRange"[From], DateFormatString ),
FormattedTo = DateTime.ToText(To, DateFormatString ),
...
(Further in the code, I will need to concart formatted datetimes in a URL string.)
If I finish with
...
in
#"TimeRange"
I get a table with DateTimes, as expected.
If I finish with
...
#"testTable" = { From, To, FormattedFrom, FormattedFrom}
in
#"testTable"
I get a table displaying
1 List
2 List
3 Error
4 Error
while I expected
3 and 4 to be date formatted as DateFormatString suggests.
I have also tried without DateFormatString as in
FormattedFrom = DateTime.ToText(#"TimeRange"[From]),
and with DateFormatString = "YYYYMMDD", as shown in example on https://msdn.microsoft.com/en-us/library/mt253497.aspx
But I got the same result.
How am I supposed to format dates ?
Edit: Error says: Expression.Error: We cannot convert a value of type
List to type DateTime. Details:
Value=List
Type=Type
DateTime.FromText expects a cell as a first argument instead of a column.
This added custom column would create a textstring that concatenates the 2 Dates with the desired format and "-" as a separator:
String = Table.AddColumn(#"TimeRange", "String", each DateTime.ToText([From], DateFormatString)&"-"&DateTime.ToText([To], DateFormatString))
Related
I have the following problem. I'm getting Data (Excel 365 - Power Query) from a Cube with "Get Data from Analysis Services". -> Selling Qty an Values for filtered years by week.
Every thing is fine if I use Filter, updatetime ca. 3-4 seconds:
#"Filtered Rows1" = Table.SelectRows(#"Added Items", each
(Cube.AttributeMemberId([#"Date.Year (4-4-5)"]) = "[Date].[Year 4-4-5].&["&
Number.ToText(2019) &"]" meta
[DisplayName = Number.ToText(2019)]
or Cube.AttributeMemberId([#"Date.Year (4-4-5)"]) = "[Date].[Year 4-4-5].&["&
Number.ToText(2020) &"]" meta
[DisplayName = Number.ToText(2020)]
)
Now I like to do that dynamic, so that I can get the years from a cell in excel. I use the following M-Function "fktGetNamedCellValue" for this:
let
Source = (FieldInput as text) =>
let Quelle = Excel.CurrentWorkbook(){[Name=FieldInput]}[Content],
Inhalt = Number.From(Quelle{0}[Column1])
in Inhalt
in Source
I replaced the years in the Filter-Step with the function.
The cells are named "cell_Prev_Year" and "cell_Plan_Year"
The cells in Excel formated as Numbers (and there are only Numbers in it)
The updatetime now -> endless!!!
#"Filtered Rows1" = Table.SelectRows(#"Added Items", each
(Cube.AttributeMemberId([#"Date.Year (4-4-5)"]) = "[Date].[Year 4-4-5].&["&
Number.ToText(fktGetNamedCellValue("cell_Prev_Year") &"]" meta
[DisplayName = Number.ToText(fktGetNamedCellValue("cell_Prev_Year"))]
or Cube.AttributeMemberId([#"Date.Year (4-4-5)"]) = "[Date].[Year 4-4-5].&["&
Number.ToText(fktGetNamedCellValue("cell_Plan_Year")) &"]" meta
[DisplayName = Number.ToText(fktGetNamedCellValue("cell_Plan_Year"))]
)
If I use a "normal" parameter with the value "2019" or "2020" everything is fine.
Only if I use the fktGetNamedCellValue it will not run correctly.
I`ed Trim an Clean the result. Formated it as Text and Number... nothing helped.
I have to use userfriendly Parameter (not set in Power Query) for this, so I hope for some help :)
Best Regards
Chris
(PS: I hope u understand my english)
I solved this problem as follows.
Since it is not an good idea to use an user-function as parameter to get data from an cube. I think this method disables query-folding or is called a lot of times in the process, I decided to use an power-query parameter.
I change this Parameter with vba by checking the worksheet_change event and calling this sub:
Sub refresh_Parameter(ParameterName As String, ParameterValue As Variant)
Dim strOldFormula As String
Dim strParametersMeta As String
strOldFormula = ThisWorkbook.Queries(ParameterName).Formula
strParametersMeta = Mid(strOldFormula, InStr(1, strOldFormula, "meta"), Len(strOldFormula))
ThisWorkbook.Queries(ParameterName).Formula = ParameterValue & " " & strParametersMeta
Debug.Print strOldFormula
Debug.Print strParametersMeta
End Sub
The parameters for the sub arte the PARAMETER Name in PowerQuery and the VALUE which should be set. For this the sub extracts the meta-data from the query-formula and combines it with the new Value.
Maybe someone needs this :)
Best regards chris
I have a workbook where I fetch data from SQL Server using fixed parameter values for a SQL query.
I want to make another sheet and have the parameter for the SQL query be taken from the cell values.
I didn't find anything on this regard.
Also I would like to refresh the data as soon as the cell values changes in the other sheet.
For this to work, you need to set up three different parts:
1) A parameter table in an Excel sheet
2) Changes to the advanced editor in PowerQuery
3) A macro to refresh the PQ when any cells in the parameter table are changed
1) Excel Table
You can see I included a column called param which can hold a Parameter name to help keep straight which parameter is which.
2) PQ Advanced Editor
let
ParamTable = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
Param = "'" & Text.From(ParamTable[value]{0}) & "'",
Source = Sql.Database("IP Address", "Database Name", [Query="Select * from weeks#(lf)where date >= '2018-01-01' and date < " &Param])
in
Source
Equivalent alternative: (Difference in location of variable used in SQL query.)
let
ParamTable = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
Param = "'" & Text.From(ParamTable[value]{0}) & "'",
Source = Sql.Database("IP Address", "Database Name", [Query="Select * from weeks#(lf)where date < " &Param & " and date >= '2018-01-01'"])
in
Source
Alternative Variable Type: (If dealing with numbers, the string markers ' aren't required)
let
ParamTable = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
Param = Text.From(ParamTable[value]{0}),
Source = Sql.Database("IP Address", "Database Name", [Query="Select * from weeks#(lf)where cnt < " &Param & " and date >= '2018-01-01'"])
in
Source
Explanation:
After pulling the Parameter Table into the PQ Query (ParamTable = Excel.CurrentWorkbook(){[Name="Table1"]}[Content]), the columns can be accessed by column name [value] and the rows by a zero-index number {0}. Since I was pulling in a date-value. I needed to convert it to a string value I could insert into the SQL Query -- thus the Text.From() and the appended ''s to the ends (SQL marks strings with single ' rather than the double ")
Since I named the variable Param, to use it in the string, I substituted &Param for the value which had originally been there.
2.1 Power Query's Value.NativeQuery
let
ParamTable = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
Param = ParamTable[value]{0},
Source = Value.NativeQuery(Sql.Database("IP Address", "Database Name"), "Select * from weeks where date < #dateSel and date >= '2018-01-01'",[dateSel = Param])
in
Source
Alternative Formatting:
let
ParamTable = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
Param = ParamTable[value]{0},
Source = Sql.Database("IP Address", "Database Name"),
Data = Value.NativeQuery(Source, "
Select * from weeks
where date < #dateSel and date >= '2018-01-01'
",[dateSel = Param])
in
Source
Notes:
When using Value.NativeQuery(), you can pass a date or datetime value directly in as a variable without having to include the single apostrophes.
Sometimes splitting the data retrieval into a Source step and a NativeQuery step can help with PQ's sporadic firewall issues.
3) Macro
This works for a simple check if anything in the table has changed, then runs the refresh. You will need to make sure this is placed in the correct module. Items you will need to change are:
Sheet1 is the codename of the worksheet with the parameter table.
"Table" is the name of the Parameter table
"Query - Query1" is the name of the connection to be refreshed
Note: Query1 is the name of the query. Default names for connections are usually Query - & query name
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Sheet1.ListObjects("Table1").DataBodyRange) Is Nothing Then
ThisWorkbook.Connections("Query - Query1").Refresh
End If
End Sub
I am trying to read a cell with possible trailing zeros as a string instead of numeric (which strips off leading zeros). The cell is read by integer column/row as below instead of column string as this answer has.
initial code
$instReader = $reader->load($this->file);
$sheet = $instReader->getSheet(0);
I tried modifying this from:
$keyCell = $sheet->getCellByColumnAndRow(1,5);
to:
$sheet->setCellValueExplicitByColumnAndRow(1,5, PHPExcel_Cell_DataType::TYPE_STRING);
$keyCell = $sheet->getCellByColumnAndRow(1,5);
the former gives 1407 for $keyCell instead of 01407
the latter gives "s" or ""
how do I treat the cell as string before calling getCellByColumnAndRow and using only integer values for column and row.
(BTW, if this can be done once for an entire column instead of each time for each individual cell that would be better)
$keyCell = $sheet->getCellByColumnAndRow(1,5)->getValue();
Will read the cell data in the format that it's actually stored by Excel, you can't arbitrarily change that or tell PHPExcel to read it as a different datatype.
However, if the cell has formatting applied, then you can use
$keyCell = $sheet->getCellByColumnAndRow(1,5)->getFormattedValue();
instead, and this will return the data as a string, with whatever format mask was defined in the Excel spreadsheet
Same issue for me. I become crazy.
Tried to set
$objReader->setReadDataOnly(true);
wasn't working
tried
$sheet->getCellByColumnAndRow(4,$row)->getValue()
because normaly display text as raw => doesn't working.
So last I change code in library. Edit file named DefaultValueBinder.php
Search for dataTypeForValue function and set this :
} elseif (is_float($pValue) || is_int($pValue)) {
return PHPExcel_Cell_DataType::TYPE_STRING;//TYPE_NUMERIC patch here;
} elseif (preg_match('/^\-?([0-9]+\\.?[0-9]*|[0-9]*\\.?[0-9]+)$/', $pValue)) {
return PHPExcel_Cell_DataType::TYPE_STRING;//TYPE_NUMERIC patch here;
So now return numbers with 0
I have a VBA script in which I am trying to convert the string in "yyyymmdd" format to "mm/dd/yyyy" format. However, when I incorporate format function to achieve this, it's showing
"Run time error-6": Overflow
Can any one help me with this ? The following is the correspondig VBA code.
// NewDate is in the format "yyyymmdd" being extracted out of a file path like "C:\Files\20140611\file.csv"
Required_format=Format(NewDate,"mm/dd/yyyy") // This line shows the error
you will have to format this yourself, because Format doesn't know that it is dealing with a date, it simply sees a string.
Use something like (psuedo code):
y = left(NewDate, 4)
m = mid(NewDate, 5, 2)
d = right(NewDate, 2)
Required_format = m + "/" + d + "/" + y
Just be absolutely sure the format is consitant. Any change (especially the padding is notorious) messes up your format.
Here is one more solution:
CDate(format(NewDate,"mm dd yyyy"))
Here's another method. As you wrote above, NewDate contains an 8 digit string representing a date in yyyymmdd format. The following "one liner" will output a date (as a string) in your desired format:
Format(Format(NewDate, "####/##/##"), "mm/dd/yyyy")
I am fetching the value present in the excel cell which is a date like 20-3-2004 using the following code:
string logResult = null;
string ResultFilePath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + ResultFile;
Microsoft.Office.Interop.Excel.Application myapp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook wb = myapp.Workbooks.Open(ResultFilePath);
Microsoft.Office.Interop.Excel.Worksheet sheet = (Microsoft.Office.Interop.Excel.Worksheet)wb.Worksheets.get_Item(1);
var cell = (Microsoft.Office.Interop.Excel.Range)sheet.Cells[row, col];
logResult = cell.Value.ToString();
but in the logresult I am always getting date in format 20/3/2004 . please suggest how get the exact format of the date which is written in the cell.
A date value has no format. It is the code that you use to display it that present that value is some form on video.
In your case, it is the ToString() call that trasform whatever has been read on the cell in a string. If it is a date then it trasform it according to the current international settings of your machine.
You could force the ToString() method to use a particular format applying a Format Mask parameter like
logResult = cell.Value.ToString("d-M-yyyy");
See the topic on MSDN about DateTime.ToString()