Re: Excel+ODBC
От: Elena_ Россия  
Дата: 19.07.04 22:15
Оценка: 3 (1)
Здравствуйте, GuinPin, Вы писали:

GP>Есть экселевская таблица — накладная.

GP>Заголовок, табличная часть и итоги.
GP>В табличной части суммы мдут без НДС, а в итогах указывается общая сумма без НДС, НДС и общая сумма с НДС.
GP>Мне необходимо выцепить сумму с НДС. Т.е. в ячейке Ехх значение "ИТОГО:", а в Dxx значение 123,45
GP>Если я правильно понимаю политику партии и народа, то наименований колонок не существует и задать в запросе условие WHERE [E]='ИТОГО:' я не могу.
GP>Ладно. Выполняю запрос SELECT * FROM [Накладная$] и пытаюсь проверить в датаридере значение пятого поля. Облом. Видимо, драйвер считает всю колонку числовой и не отдает строковые значения.

На самом деле если OdbcConnection, то как раз всегда берутся заголовки из первой строки диапазона —

см. BUG: Excel ODBC Driver Disregards the FirstRowHasNames or Header Setting Q288343

The value of the FirstRowHasNames or Header (HDR) parameter is never being passed to the Excel ODBC Driver.

The HDR= setting is available and functional when you use the Microsoft Jet OLE DB Provider and its Excel ISAM driver. Therefore, the best solution is to use the Jet Provider rather than the Excel ODBC driver.

Because the Excel ODBC driver always assumes that the first row contains field names, the first row must always contain either valid field names, or dummy entries that the developer is willing to disregard.


И при этом всегда можно использовать типа WHERE <Значение в первой строке диапазона> =

Если использовать OleDbConnection, то можно брать заголовки из первой строки диапазона или не брать.

см., например, HOWTO: Use ADO with Excel Data from Visual Basic or VBA Q257819

Column headings: By default, it is assumed that the first row of your Excel data source contains columns headings that can be used as field names. If this is not the case, you must turn this setting off, or your first row of data "disappears" to be used as field names. This is done by adding the optional HDR= setting to the Extended Properties of the connection string. The default, which does not need to be specified, is HDR=Yes. If you do not have column headings, you need to specify HDR=No; the provider names your fields F1, F2, etc. Because the Extended Properties string now contains multiple values, it must be enclosed in double quotes itself, plus an additional pair of double quotes to tell Visual Basic to treat the first set of quotes as literal values, as in the following example (where extra spaces have been added for visual clarity).

.ConnectionString = "Data Source=C:\MyFolder\MyWorkbook.xls;" & _
"Extended Properties=" " Excel 8.0; HDR=No;" " "


То есть WHERE всегда можно использовать — или WHERE [<Значение в первой строке диапазона>] ... или WHERE F1 ...

Но, если в начале идут числовые значения, то дальнейшие Итого будут восприниматься как NULL. Если нечисловое значение в строке одно, то можно накладывать условие типа F1 IS NULL, если их несколько —

также см., например, HOWTO: Use ADO with Excel Data from Visual Basic or VBA Q257819

Considerations That Apply to Both OLE DB Providers
A Caution about Mixed Data Types

As stated previously, ADO must guess at the data type for each column in your Excel worksheet or range. (This is not affected by Excel cell formatting settings.) A serious problem can arise if you have numeric values mixed with text values in the same column. Both the Jet and the ODBC Provider return the data of the majority type, but return NULL (empty) values for the minority data type. If the two types are equally mixed in the column, the provider chooses numeric over text.

For example:
In your eight (8) scanned rows, if the column contains five (5) numeric values and three (3) text values, the provider returns five (5) numbers and three (3) null values.
In your eight (8) scanned rows, if the column contains three (3) numeric values and five (5) text values, the provider returns three (3) null values and five (5) text values.
In your eight (8) scanned rows, if the column contains four (4) numeric values and four (4) text values, the provider returns four (4) numbers and four (4) null values.
As a result, if your column contains mixed values, your only recourse is to store numeric values in that column as text, and to convert them back to numbers when needed in the client application by using the Visual Basic VAL function or an equivalent.

To work around this problem for read-only data, enable Import Mode by using the setting "IMEX=1" in the Extended Properties section of the connection string. This enforces the ImportMixedTypes=Text registry setting. However, note that updates may give unexpected results in this mode. For additional information about this setting, click the article number below to view the article in the Microsoft Knowledge Base:
Q194124 PRB: Excel Values Returned as NULL Using DAO OpenRecordset


То есть для OleDBConnection добавляете IMEX=1; и условие F1 = 'ИТОГО', для OdbcConnection — не знаю аналога.
Пользователь — друг программиста!
Excel+ODBC
От: GuinPin  
Дата: 19.07.04 12:48
Оценка:
Есть экселевская таблица — накладная.
Заголовок, табличная часть и итоги.
В табличной части суммы мдут без НДС, а в итогах указывается общая сумма без НДС, НДС и общая сумма с НДС.
Мне необходимо выцепить сумму с НДС. Т.е. в ячейке Ехх значение "ИТОГО:", а в Dxx значение 123,45
Если я правильно понимаю политику партии и народа, то наименований колонок не существует и задать в запросе условие WHERE [E]='ИТОГО:' я не могу.
Ладно. Выполняю запрос SELECT * FROM [Накладная$] и пытаюсь проверить в датаридере значение пятого поля. Облом. Видимо, драйвер считает всю колонку числовой и не отдает строковые значения.
 tmpCommE.CommandText = "SELECT * From [Накладная$]"
    tmpReader = tmpCommE.ExecuteReader(CommandBehavior.CloseConnection)
     If tmpReader.HasRows Then
       While tmpReader.Read
       If Not(tmpReader(4).GetType Is GetType(DBNull)) Then
          If CStr(tmpReader(4)) = "Итого:" Then
            GT = tmpReader(5)
              Exit While
          End If
       End If
      End While
     End If

А как разрулиться? OLE не подходит, т.к. медленный, а файлов очень много. Расчетный метод тоже не прокатывает, т.к. ставки налога менялись (накладные за несколько лет).
... << RSDN@Home 1.1.3 stable >>
С уважением, Сошников Иван
 
Подождите ...
Wait...
Пока на собственное сообщение не было ответов, его можно удалить.