Ошибка power query dataformat error

Файлы к уроку:

Файлы к уроку:

  • Для спонсоров Boosty
  • Для спонсоров VK
  • YouTube
  • VK

Ссылки:

  • Страница курса
  • Плейлист YouTube
  • Плейлист ВК

Описание

Мы собираемся импортировать таблицу с этой страницы. Когда мы пытаемся изменить тип данных для столбцов с датой, то возвращается столбец с ошибкой DateFormat.Error.

Решение

Если не получается преобразовать столбец с текстом в дату, то значит в строке присутствуют лишние символы.

С помощь функции Text.Length мы можем убедиться, что длина строки намного больше, чем ожидается. Мы видим 10 символов, но функция возвращает 15.

С помощью функции Text.Start извлечем 1 символ сначала строки. Потом получим код этого символа с помощью функции Character.ToNumber. Получаем 8206.

Далее воспользуемся функционалом замены подстроки и исправляем получившуюся формулу:

Table.ReplaceValue(
      get_table, 
      Character.FromNumber(8206), 
      "", 
      Replacer.ReplaceText, 
      {
         "Дата начала купонного периода", 
         "Дата выплаты купона", 
         "Дата фиксации списка держателей"
      }
   )

Примененные функции

  • Text.Length
  • Text.Start
  • Character.ToNumber
  • Web.Page
  • Web.Contents
  • Table.SelectRows
  • Table.ReplaceValue
  • Character.FromNumber
  • Replacer.ReplaceText
  • Table.TransformColumnTypes

Код

let
   source = Web.Page(
      Web.Contents(
         "https://www.moex.com/ru/issue.aspx?board=TQCB&code=RU000A102036#/bond_4"
      )
   ), 
   get_table = Table.SelectRows(
      source, 
      each ([ClassName] = "coupon-payment-schedule__table")
   ){0}[Data], 
   cols_replace = Table.ReplaceValue(
      get_table, 
      Character.FromNumber(8206), 
      "", 
      Replacer.ReplaceText, 
      {
         "Дата начала купонного периода", 
         "Дата выплаты купона", 
         "Дата фиксации списка держателей"
      }
   ), 
   cols_types = Table.TransformColumnTypes(
      cols_replace, 
      {
         {"Дата начала купонного периода", type date}, 
         {"Дата выплаты купона", type date}, 
         {"Дата фиксации списка держателей", type date}
      }
   )
in
   cols_types

Этот урок входит в курс Работа с ошибками в Power Query

Номер урока Урок Описание
1 Power Query Ошибки №1. Измененный тип, Неверная фильтрация в UI Почему возникает ошибка Expression.Error Столбец таблицы не найден? Одна из причин — шаг Измененный тип.
Почему в вашей итоговой таблицы не все данные, которые должны там оказаться? Вероятно вы совершили ошибку неверной фильтрации в пользовательском интерфейсе.
2 Power Query Ошибки №2. Фиксированная ширина столбца Excel В этом уроке вы узнаете как отключить автоматическое определение ширины столбцов таблицы Excel при обновлении запроса Power Query.
3 Power Query Ошибки №3. Formula Firewall, запрос ссылается на… Вы работаете в Power Query, но при попытке обновить все возникает ошибка Formula Firewall, запрос ссылается на… Что делать? Как исправить?
4 Power Query Ошибки №4. Доступ к веб-содержимому В этом уроке вы узнаете как избавиться от надоедливого окна доступ к веб-содержимому.
5 Power Query Ошибки №5. Количество столбцов CSV При импорте CSV получается неверное количество столбцов.
6 Power Query Ошибки №6. Не получается изменить тип данных (DataFormat.Error) При попытке изменить тип данных с текстового на дату возникает ошибка DataFormat.Error.
7 Power Query Ошибки №7. Разные имена листов В этом уроке мы решим проблему, когда в ваших источниках нужные вам данные находятся всегда на листах с разными именами.
8 Power Query Ошибки №8. Разные имена листов 2 В этом уроке мы другими способами решим проблему, когда в ваших источниках нужные вам данные находятся всегда на листах с разными именами.
9 Power Query Ошибки №9. Разные имена столбцов, Table.TransformColumnNames В этом уроке мы разберем проблему, когда нам присылают файлы, в которых всегда столбцы названы по-разному.
10 Power Query Ошибки №10. Как развернуть все столбцы В этой задаче мы научимся разворачивать все столбцы табличного столбца не перечисляя каждый из них хардкодом.
11 Power Query Ошибки №11. Подключиться к последнему файлу В этом уроке мы научимся подключаться к самому свежему файлу из нужной нам папки с нужным названием.
12 Power Query Ошибки №12. Консолидация и MissingField.Type Бывает вы ходите выполнить добавление таблиц друг под другом с предварительной обработкой, но получаете ошибку Expression.Error: Столбец таблицы не найден.
13 Power Query Ошибки №13. Удалить пустые столбцы Как без хардкода автоматически удалить пустые столбцы в Power Query, которые есть в импортируемой таблицы. Разберем 2 способа. Один из них прост до безобразия, а для второго понадобится функция Table.Profile.
14 Power Query Ошибки №14. Удалить лишние пробелы В этом уроке мы разберем еще 1 способ удалить лишние пробелы в текстовом столбце Power Query. Для этого мы повторим и изучим несколько новых функций.
Text.SplitAny
List.Select
Character.FromNumber
Text.Combine
15 Power Query Ошибки №15. Плохо структурированный TXT Как быть, если текстовый файл разбивается на столбцы неправильно?
16 Power Query Ошибки №16. При округлении не совпадает общая сумма Разберем ошибку, которая возникает при необходимости разбить число на определенные доли, а результаты округлить до двух знаков после запятой. В такой ситуации может получиться, что сумма слагаемых не будет равняться исходному числу.
17 Power Query Ошибки №17. Удаление дубликатов, Подводные камни Table. Distinct Что может пойти не так при использовании функции удаления дубликатов.
18 Power Query Ошибки №18. Удаление дубликатов 2, Подводные камни Table. Distinct Что может пойти не так при использовании функции удаления дубликатов. Другое решение данной проблемы.
19 Power Query Ошибки №19. Неверная разбивка на столбцы При импорте данных из CSV или TXT разбивка на столбцы происходит неправильно.
20 Power Query Ошибки №20. Пустая таблица при импорте Excel (XLSX, XLS) Вы пытаетесь подключиться к книге Excel, но импортируется пустая таблица.
21 Power Query Ошибки №21. Подключение к PostgreSQL, Установка драйвера Вы пытаетесь подключиться к PostgreSQL и получаете ошибку «Перед использование этого соединителя необходимо установить один или несколько дополнительных компонентов»

  • All forum topics


  • Previous Topic

  • Next Topic

Griffin_BI

  • Mark as New
  • Bookmark
  • Subscribe
  • Mute
  • Subscribe to RSS Feed
  • Permalink
  • Print
  • Report Inappropriate Content

‎06-18-2021

07:35 AM

Hello, 

I am connecting to an excel workbook on sharepoint using the web connector. I have a column of number values e.g. 1 of the «ABC 123» type when they come in. When I try to change this to «123» number I get an error message saying DataFormat.Error: We couldn’t convert to Number. I don’t understand how this could fail. Any ideas please?

Griffin_BI_0-1624026848011.png


Message 1 of 5

10,905 Views

2 ACCEPTED SOLUTIONS

edhans

  • Mark as New
  • Bookmark
  • Subscribe
  • Mute
  • Subscribe to RSS Feed
  • Permalink
  • Print
  • Report Inappropriate Content

‎06-18-2021

09:13 AM

Because something in that column isn’t a number. There is a non-numeric character in that column. Here I have created a table with the numbers 1-6, then a letter, then converted to a number.

edhans_0-1624032610094.png

It tells you at the bottom in the error code — Details: a — «a» was the character I typed in.
You need to either filter out that value first, replace it with something else using the Replace Values feature on the Transform ribbon, or fix the source data first.

Note you could have invisible data. If you paste data from a website, HTML will add all sorts of garbage to a cell in Excel that Power Query will have none of, but it is non-printing and often you cannot see it. You have to use CODE() in Excel to find it, or Character.ToNumber() in Power Query. ASCII char 160 is a good example of this.

Did I answer your question? Mark my post as a solution!
Did my answers help arrive at a solution? Give it a kudos by clicking the Thumbs Up!

DAX is for Analysis. Power Query is for Data Modeling

Proud to be a Super User!

MCSA: BI Reporting


Message 2 of 5

10,860 Views

V-pazhen-msft

  • Mark as New
  • Bookmark
  • Subscribe
  • Mute
  • Subscribe to RSS Feed
  • Permalink
  • Print
  • Report Inappropriate Content

‎06-21-2021

07:57 PM

If your cell contains text any string, it would be the error. Try split the text and number stings. 

For example, if you have «ab 100» in a column cell, you can split it by blank and then turn the column with 100 into number type.

Paul Zheng _ Community Support Team
If this post helps, please Accept it as the solution to help the other members find it more quickly.


Message 4 of 5

10,807 Views


  • All forum topics


  • Previous Topic

  • Next Topic

4 REPLIES 4

RR_25

  • Mark as New
  • Bookmark
  • Subscribe
  • Mute
  • Subscribe to RSS Feed
  • Permalink
  • Print
  • Report Inappropriate Content

‎01-12-2022

07:37 AM

RR_25_0-1642001710308.png

Hi Community,

I dont know if this is already asked here, i just cant fix the errors. I tried removed errors but it still there.

«DataFormat.Error: We couldn’t convert to Number. Details: not in SMART»

Please help on this. thank you!


Message 5 of 5

9,326 Views

V-pazhen-msft

  • Mark as New
  • Bookmark
  • Subscribe
  • Mute
  • Subscribe to RSS Feed
  • Permalink
  • Print
  • Report Inappropriate Content

‎06-21-2021

07:57 PM

If your cell contains text any string, it would be the error. Try split the text and number stings. 

For example, if you have «ab 100» in a column cell, you can split it by blank and then turn the column with 100 into number type.

Paul Zheng _ Community Support Team
If this post helps, please Accept it as the solution to help the other members find it more quickly.


Message 4 of 5

10,808 Views

watkinnc

  • Mark as New
  • Bookmark
  • Subscribe
  • Mute
  • Subscribe to RSS Feed
  • Permalink
  • Print
  • Report Inappropriate Content

‎06-18-2021

11:53 AM

I would try selecting the column, then choose from the Format Dropdown in the GUI «Clean» which will remove all non-printable characters.

—Nate

I’m usually answering from my phone, which means the results are visualized only in my mind. You’ll need to use my answer to know that it works—but it will work!!


Message 3 of 5

10,850 Views

edhans

  • Mark as New
  • Bookmark
  • Subscribe
  • Mute
  • Subscribe to RSS Feed
  • Permalink
  • Print
  • Report Inappropriate Content

‎06-18-2021

09:13 AM

Because something in that column isn’t a number. There is a non-numeric character in that column. Here I have created a table with the numbers 1-6, then a letter, then converted to a number.

edhans_0-1624032610094.png

It tells you at the bottom in the error code — Details: a — «a» was the character I typed in.
You need to either filter out that value first, replace it with something else using the Replace Values feature on the Transform ribbon, or fix the source data first.

Note you could have invisible data. If you paste data from a website, HTML will add all sorts of garbage to a cell in Excel that Power Query will have none of, but it is non-printing and often you cannot see it. You have to use CODE() in Excel to find it, or Character.ToNumber() in Power Query. ASCII char 160 is a good example of this.

Did I answer your question? Mark my post as a solution!
Did my answers help arrive at a solution? Give it a kudos by clicking the Thumbs Up!

DAX is for Analysis. Power Query is for Data Modeling

Proud to be a Super User!

MCSA: BI Reporting


Message 2 of 5

10,861 Views

Just like any other language, Power Query has its own different types of errors, one of them is DataFormat Error.

Dataformat errors in Power Query are mostly data type errors and do not prevent you from loading data to Power BI, instead the cells will be loaded as blank. The screenshot below shows 3 errors for 78 records when the data is loaded to Power BI.

To audit the error or get more details, do the following:

  1.  Click on View errors from above to go back to Power Query Editor
  2. In Power Query Editor-> Select View tab -> Check Column Quality

For this example, UnitsInStock has 3% error for all rows in that column.

3. Click on Kept Errors under Applied Steps to see only rows with errors, the Kept Errors step is automatically added when you click on View errors from step 1.

Below screenshot show 100% error for the 3 rows.

4. To see details of the error, select the error as seeing below:

For this example, the error occurs because the column data type is Number, but 3 rows in the column has Text values, Power Query return error because it cannot convert the Text values to Numbers.

DataFormat.Error: We couldn’t convert to Number

5. To audit the error, create a custom column using the try expression, from Add column -> Custom Column -> type the expression below. A new Record column will be created.

6. Click on Expand -> Select Error

7. Click Expand again -> Click OK

You will see the Reason, Message and Detail of the error. You can load the error details to Power BI and create an Audit report if needed.

Also, you can use this report to make changes to the affected values at Data source level and reload to Power BI.

8. To replace the errors in Power Query from Advanced Editor, add a line of code to the MQuery with the value to replace with.

For this example, I am replacing all errors with 0. Optionally, you can replace the errors by right clicking the column, then select Replace Error.

Note: Those new values from Power Query will not be updated to your source data.

9. Click on Enable Load to load the data to Power BI if its not enabled by default, right click on the query from the left and select Enable load.

10. Click Close and Apply

The data will now load and apply all changes successfully without errors.

Happy Auditing! 🙂

  • Remove From My Forums
  • Question

  • I’m having an issue with filtering a specific column to show only empty rows. I’ve tried multiple different fixes, and none seem to work. 

    I’ll paste the whole query below, but the trouble spot is here:  

     #»Filtered Rows» = Table.SelectRows(#»Changed Type», each ([Assigned User] <> null))

    I’ve tried changing to 

     #»Filtered Rows» = Table.SelectRows(#»Changed Type», each ([Assigned User] = null))

    and 

     #»Filtered Rows» = Table.SelectRows(#»Changed Type», each ([Assigned User] is null))

    In both cases when I attempt to load the data, I get the «[DataFormat.Error] We couldn’t convert to Number» pop up. The preview is working on the query; it’s only happening when I attempt to lad. the specific column is a Text Column, and the source
    tables are both set as text as well. 

    I also get this error if I move the filter in the original query to later in the steps. Any ideas? 

    Here’s the full query: 

    let
        Source = Table.NestedJoin(IHIE_MHIN_Combined,{«MRN»},Prod_and_CM_For_Query,{«MRN»},»Prod_and_CM_For_Query»,JoinKind.LeftOuter),
        #»Expanded Prod_and_CM_For_Query» = Table.ExpandTableColumn(Source, «Prod_and_CM_For_Query», {«Product», «Assigned User»}, {«Product», «Assigned User»}),
        #»Reordered Columns» = Table.ReorderColumns(#»Expanded Prod_and_CM_For_Query»,{«Source.Name», «ADMITTYPE», «Product», «Assigned User», «MRN», «LASTNAME», «FIRSTNAME»,
    «DOB», «DATE_OF_DEATH», «SSN», «ADDRESS1», «ADDRESS2», «CITY», «STATE», «ZIPCODE», «ADMIT_DATE», «DISCHARGE_DATE», «CHIEFCOMPLAINT», «DIAGNOSES_CODES»,
    «DIAGNOSES_DESCRIPTIONS», «INSTITUTIONNAME», «ORGANIZATIONFORMALNAME», «LOCATIONFORMALNAME», «LOCATIONDESCRIPTION», «ATTENDINGNAME», «PHONE», «ENCOUNTER_ID», «ATTENDING_NPI»}),
        #»Changed Type» = Table.TransformColumnTypes(#»Reordered Columns»,{{«DOB», type date}, {«DATE_OF_DEATH», type date}, {«ADMIT_DATE», type date}, {«DISCHARGE_DATE», type date}, {«PHONE»,
    type text}, {«ENCOUNTER_ID», type text}}),
        #»Filtered Rows» = Table.SelectRows(#»Changed Type», each ([Assigned User] <> null)),
        #»Inserted Merged Column» = Table.AddColumn(#»Filtered Rows», «Merged», each Text.Combine({[Source.Name], [ADMITTYPE], [Product], [Assigned User], [MRN], [LASTNAME], [FIRSTNAME], Text.From([DOB], «en-US»),
    Text.From([DATE_OF_DEATH], «en-US»), [SSN], [ADDRESS1], [ADDRESS2], [CITY], [STATE], Text.From([ZIPCODE], «en-US»), Text.From([ADMIT_DATE], «en-US»), Text.From([DISCHARGE_DATE], «en-US»), [CHIEFCOMPLAINT], [DIAGNOSES_CODES],
    [DIAGNOSES_DESCRIPTIONS], [INSTITUTIONNAME], [ORGANIZATIONFORMALNAME], [LOCATIONFORMALNAME], [LOCATIONDESCRIPTION], [ATTENDINGNAME], [PHONE], Text.From([ENCOUNTER_ID], «en-US»), Text.From([ATTENDING_NPI], «en-US»)}, «»), type
    text),
        #»Removed Duplicates» = Table.Distinct(#»Inserted Merged Column», {«Merged»}),
        #»Removed Columns» = Table.RemoveColumns(#»Removed Duplicates»,{«Merged»}),
        #»Filtered Rows1″ = Table.SelectRows(#»Removed Columns», each ([Product] <> null))
    in
        #»Filtered Rows1″

Answers

  • Hi there, 

    sorry for the delayed response. I have multiple data sources and queries going in this book. Two queries grab .txt files and convert them into the right format to start parsing through the data. Another query pulls from a shared report on SharePoint, and
    another pulls from an Excel file (also saved to SharePoint). These are then merged/appended in various ways to get to the outputs we need. 

    I was able to fix the error, however. To do so, though, I had to go to each of the queries and convert all the columns to text. Not ideal, but I get the info I need. 

    • Marked as answer by

      Friday, November 10, 2017 2:25 PM

    • Unmarked as answer by
      Ehren — MSFTMicrosoft employee
      Friday, November 10, 2017 5:38 PM
    • Marked as answer by
      RobVanWinkle
      Tuesday, December 5, 2017 4:46 PM

  • Hi Rob,

    For your description, it sounds like there is some non-numeric data in some of the rows that you were previously converting to number. The problematic cells may be beyond the first chunk of rows PQ displays in the preview, but are likely being encountered
    when doing the filter.

    I’d recommend you examine the source data to determine where the errors are coming from, remove or fix up the problematic rows, and then re-apply the number conversion.

    Ehren

    • Edited by
      Ehren — MSFTMicrosoft employee
      Friday, November 10, 2017 6:01 PM
    • Proposed as answer by
      Imke FeldmannMVP
      Saturday, November 11, 2017 10:33 AM
    • Marked as answer by
      RobVanWinkle
      Tuesday, December 5, 2017 4:46 PM

Fix Error When Reading XLSB File In Power Query

A XLSB File error can come to you by surprise. Recently one of my clients built a Power Query solution. In one of the steps, the query ran into an unknown error. The query started with data from a CSV file. And then merges different Excel files to enrich the dataset. One of the merges results in the following error message.

“An error occurred in the ‘TBL_MAPPING_B2G’ query. DataFormat.Error: External table is not in the expected format. Details: TBL_MAPPING_B2G.xlsb”

This message indicates the name of the Query that causes an error. Yet it’s not very clear what’s going on. The table is not in the expected format…

Error Checking

So I did some basic error checking. This was my approach.

  1. First I examined the source data. Does the source data contain any errors? Strange formatting? Perhaps symbols that are not accepted? Inspecting the source file didn’t give me any indication of strange symbols or errors. Data seemed structured, without errors or strange symbols.
  2. Next, I looked at what the query looked like after importing it in Power Query. Are columns perhaps defined with the wrong data type? Do errors occur in any of the columns? Again, I found nothing noteworthy.
  3. The error message occurs in the step where the base query merged with ‘TBL_MAPPING_B2G’. To make sure nothing went wrong there, I perform the merge once more by deleting the old step and doing the merge again. The error message appeared again. The riddle continued.

I’m slowly running out of ideas. The query involves many different merges. So how is this particular merge different from the others?

Solution

The clue to the solution appeared when inspecting the source files. The merge resulting in an error is the only file saved with a .XLSB file type. All other files types are either .XLSX or .CSV.

Perhaps this influences how Power Query reads the data. Since the file causing the error contains macro’s, I save it as .XLSM. Next I change the source file in Power Query, press refresh and VOILA! The error message is gone!

That’s strange. The error message indicates the table is not in the expected format, yet changing the file extension solves the problem.

The exact reason of the XLSB File Error is still unclear to me. It appears there is a bug in Power Query when reading the .XLSB file. Yet changing the file type seems to solve the issue.

Checking Google for similar issues doesn’t give much input either. It’s not much, but on this page someone seems to have a similar problem. Until it’s fixed, the way to go is to change the file format.

Have you experienced similar issues? And what was your solution to it? Please let me know in the comments below. Also make sure to check out how to import files from a Folder if you want to expand your Power Query superpowers!

Понравилась статья? Поделить с друзьями:
  • Ошибка postgresql unable to write inside temp environment variable path
  • Ошибка post 400
  • Ошибка port 443
  • Ошибка poo14 на шевроле круз
  • Ошибка poff преобразователя частотника