VB, OLE и Array.

Clarion, Clarion 7

Модератор: Дед Пахом

Правила форума
При написании вопроса или обсуждении проблемы, не забывайте указывать версию Clarion который Вы используете.
А так же пользуйтесь спец. тегами при вставке исходников!!!
kreator
✯ Ветеран ✯
Сообщения: 5037
Зарегистрирован: 28 Май 2009, 15:54
Откуда: Москва
Благодарил (а): 7 раз
Поблагодарили: 23 раза

VB, OLE и Array.

Сообщение kreator »

Работаем с Excel через OLE. Нужно воспользоваться методом OpenText. У него есть аргумент типа Array(). Как это дело перевести в синтаксис Clarion'а?
We are hard at work… for you. :)
Аватара пользователя
muskin
Активист
Сообщения: 114
Зарегистрирован: 08 Декабрь 2009, 21:16
Откуда: РК

Re: VB, OLE и Array.

Сообщение muskin »

В Excel 2010 по поиску набрал OpenText - никаких эмоций. Поясни, что это за метод и его аргумент?
Всем пралитарское Спасибо и 'Желаю, чтобы ВСЕ !!!'
Аватара пользователя
muskin
Активист
Сообщения: 114
Зарегистрирован: 08 Декабрь 2009, 21:16
Откуда: РК

Re: VB, OLE и Array.

Сообщение muskin »

Извиняюсь за забывчивость, но есть непотопляемый VB!
OpenText с указанием текстового файла и необходимых параметров -> создает новую Книгу и в ней Лист (из текстового файла перегоняем значения во вновь создаваемый лист Книги) -> получаем результат.
Аргумента Array() так и не нашел.
Kreator, может уточнишь, что должно быть на входе и должно быть на выходе?
Последний раз редактировалось muskin 02 Октябрь 2012, 3:03, всего редактировалось 1 раз.
Всем пралитарское Спасибо и 'Желаю, чтобы ВСЕ !!!'
kreator
✯ Ветеран ✯
Сообщения: 5037
Зарегистрирован: 28 Май 2009, 15:54
Откуда: Москва
Благодарил (а): 7 раз
Поблагодарили: 23 раза

Re: VB, OLE и Array.

Сообщение kreator »

Вот метод, который создает Excel:

Код: Выделить всё

Sub Макрос()
'
' Макрос1 Макрос
'

'
    ChDir "D:\Test"
    Workbooks.OpenText Filename:="D:\Test\5.txt", Origin:=1251, StartRow _
        :=1, DataType:=xlDelimited, TextQualifier:=xlDoubleQuote, _
        ConsecutiveDelimiter:=False, Tab:=True, Semicolon:=False, Comma:=False _
        , Space:=False, Other:=False, FieldInfo:=Array(Array(1, 2), Array(2, 2), _
        Array(3, 2), Array(4, 2), Array(5, 2), Array(6, 2), Array(7, 2), Array(8, 1), Array(9, 1), _
        Array(10, 1), Array(11, 1), Array(12, 1), Array(13, 1), Array(14, 1), Array(15, 1), Array( _
        16, 1), Array(17, 1), Array(18, 1), Array(19, 1), Array(20, 1), Array(21, 1), Array(22, 1), _
        Array(23, 1), Array(24, 1), Array(25, 1), Array(26, 1), Array(27, 1), Array(28, 1), Array( _
        29, 1), Array(30, 1), Array(31, 1), Array(32, 1), Array(33, 1), Array(34, 1), Array(35, 1), _
        Array(36, 1), Array(37, 1), Array(38, 1), Array(39, 1), Array(40, 1), Array(41, 1), Array( _
        42, 1), Array(43, 1), Array(44, 1), Array(45, 1), Array(46, 1), Array(47, 1), Array(48, 1), _
        Array(49, 1), Array(50, 1)), TrailingMinusNumbers:=True
End Sub
А вот его описание:

Код: Выделить всё

Excel Developer Reference 
Workbooks.OpenText Method 
Loads and parses a text file as a new workbook with a single sheet that contains the parsed text-file data.
Syntax

expression.OpenText(Filename, Origin, StartRow, DataType, TextQualifier, ConsecutiveDelimiter, Tab, Semicolon, Comma, Space, Other, OtherChar, FieldInfo, TextVisualLayout, DecimalSeparator, ThousandsSeparator, TrailingMinusNumbers, Local)

expression   A variable that represents a Workbooks object.

Parameters

Name Required/Optional Data Type Description 
Filename Required String Specifies the file name of the text file to be opened and parsed. 
Origin Optional Variant Specifies the origin of the text file. Can be one of the following XlPlatform constants: xlMacintosh, xlWindows, or xlMSDOS. Additionally, this could be an integer representing the code page number of the desired code page. For example, "1256" would specify that the encoding of the source text file is Arabic (Windows). If this argument is omitted, the method uses the current setting of the File Origin option in the Text Import Wizard. 
StartRow Optional Variant The row number at which to start parsing text. The default value is 1. 
DataType Optional Variant Specifies the column format of the data in the file. Can be one of the following XlTextParsingType constants: xlDelimited or xlFixedWidth. If this argument is not specified, Microsoft Excel attempts to determine the column format when it opens the file. 
TextQualifier Optional XlTextQualifier Specifies the text qualifier. 
ConsecutiveDelimiter Optional Variant True to have consecutive delimiters considered one delimiter. The default is False. 
Tab Optional Variant True to have the tab character be the delimiter (DataType must be xlDelimited). The default value is False. 
Semicolon Optional Variant True to have the semicolon character be the delimiter (DataType must be xlDelimited). The default value is False. 
Comma Optional Variant True to have the comma character be the delimiter (DataType must be xlDelimited). The default value is False. 
Space Optional Variant True to have the space character be the delimiter (DataType must be xlDelimited). The default value is False. 
Other Optional Variant True to have the character specified by the OtherChar argument be the delimiter (DataType must be xlDelimited). The default value is False. 
OtherChar Optional Variant (required if Other is True). Specifies the delimiter character when Other is True. If more than one character is specified, only the first character of the string is used; the remaining characters are ignored. 
FieldInfo Optional Variant An array containing parse information for individual columns of data. The interpretation depends on the value of DataType. When the data is delimited, this argument is an array of two-element arrays, with each two-element array specifying the conversion options for a particular column. The first element is the column number (1-based), and the second element is one of the XlColumnDataType constants specifying how the column is parsed. 
TextVisualLayout Optional Variant The visual layout of the text. 
DecimalSeparator Optional Variant The decimal separator that Microsoft Excel uses when recognizing numbers. The default setting is the system setting. 
ThousandsSeparator Optional Variant The thousands separator that Excel uses when recognizing numbers. The default setting is the system setting. 
TrailingMinusNumbers Optional Variant Specify True if numbers with a minus character at the end should be treated as negative numbers. If False or omitted, numbers with a minus character at the end are treated as text. 
Local Optional Variant Specify True if regional settings of the machine should be used for separators, numbers and data formatting. 

Remarks


FieldInfo Parameter Information

You can use xlEMDFormat only if you have installed and selected Taiwanese language support. The xlEMDFormat constant specifies that Taiwanese era dates are being used.

The column specifiers can be in any order. If there's no column specifier for a particular column in the input data, the column is parsed with the General setting.

  Notes 
 

If you specify that a column is to be skipped, you must explicitly state the type for all remaining columns or the data will not parse correctly.
If there is a recognizible date in the data, the cell will be formatted as a date in the worksheet even if the setting for the column is General. Additionally, if you specify one of the above date formats for a column and the data does not contain a recognized date, then the cell format in the worksheet will be General.
This example causes the third column to be parsed as MDY (for example, 01/10/1970), the first column to be parsed as text, and the remaining columns in the source data to be parsed with the General setting.

Array(Array(3, 3), Array(1, 2)) 

If the source data has fixed-width columns, the first element in each two-element array specifies the position of the starting character in the column (as an integer; character 0 (zero) is the first character). The second element in the two-element array specifies the parse option for the column as a number between 0 and 9, as listed in the preceding table.

ThousandsSeparator Parameter Information

The following table shows the results of importing text into Excel for various import settings. Numeric results are displayed in the rightmost column.

System decimal separator System thousands separator Decimal separator value Thousands separator value Text imported Cell value (data type) 
Period Comma Comma Period 123.123,45 123,123.45 (numeric) 
Period Comma Comma Comma 123.123,45 123.123,45 (text) 
Comma Period Period Comma 123,123.45 123,123.45 (numeric) 
Period Comma Period Comma 123 123.45 123 123.45 (text) 
Period Comma Period Space 123 123.45 123,123.45 (numeric) 


Example


This example opens the file Data.txt and uses tab delimiters to parse the text file into a worksheet.

Visual Basic for Applications 
Workbooks.OpenText filename:="DATA.TXT", _
    dataType:=xlDelimited, tab:=True 

Интересует переменная FieldInfo.
We are hard at work… for you. :)
Аватара пользователя
muskin
Активист
Сообщения: 114
Зарегистрирован: 08 Декабрь 2009, 21:16
Откуда: РК

Re: VB, OLE и Array.

Сообщение muskin »

Могу ошибаться, но FieldInfo (по памяти) - это значение строки, с начала которой будут заполняться поля в Excel при считывании файла.txt
И все-таки, вопрос остался в подвиснутом состоянии - что должно быть на входе и выходе?
Поверьте мне, в выше приведенном макросе никто не будет разбираться, тем более в Help-е из VS-2008.
Всем пралитарское Спасибо и 'Желаю, чтобы ВСЕ !!!'
kreator
✯ Ветеран ✯
Сообщения: 5037
Зарегистрирован: 28 Май 2009, 15:54
Откуда: Москва
Благодарил (а): 7 раз
Поблагодарили: 23 раза

Re: VB, OLE и Array.

Сообщение kreator »

FieldInfo отвечает за форматирование столбца. T.e. Array(5,2) - означает, что формат пятого столбца - текстовый.
We are hard at work… for you. :)
Аватара пользователя
muskin
Активист
Сообщения: 114
Зарегистрирован: 08 Декабрь 2009, 21:16
Откуда: РК

Re: VB, OLE и Array.

Сообщение muskin »

kreator писал(а):FieldInfo отвечает за форматирование столбца. T.e. Array(5,2) - означает, что формат пятого столбца - текстовый.
Уважаемый Kreator, попытался разобраться в макросе, но FieldInfo еще тянет за собой DataType.
Все-таки, что должно быть на входе и должно быть на выходе, может задачка решается проще?
Я не понимаю, это сверхсекретный проект? Я прошу ответить лишь на один вопрос - что на входе и что на выходе?
Всем пралитарское Спасибо и 'Желаю, чтобы ВСЕ !!!'
kreator
✯ Ветеран ✯
Сообщения: 5037
Зарегистрирован: 28 Май 2009, 15:54
Откуда: Москва
Благодарил (а): 7 раз
Поблагодарили: 23 раза

Re: VB, OLE и Array.

Сообщение kreator »

Всё просто. Закачиваем огромный текстовый файл в Excel. Если использовать метод Open (что и было раньше), то нарываемся на встроенное форматирование Excel'я (например, строку '9021-01-01' он переводит в дату '01.01.9021'), которое обратно не откатить. Чтобы этого не было, нужно задавать формат столбца "текстовый", а не "общий". Это можно сделать методом OpenText. Вот. А там такой Array :D . Можно сделать вставляя и форматируя каждую ячейку через OLE, только время вырастает ну уж очень сильно. Поэтому, поскольку форматирования особого не надо, хорошо было бы ограничиться методом OpenText.
We are hard at work… for you. :)
Аватара пользователя
muskin
Активист
Сообщения: 114
Зарегистрирован: 08 Декабрь 2009, 21:16
Откуда: РК

Re: VB, OLE и Array.

Сообщение muskin »

kreator писал(а):Всё просто. Закачиваем огромный текстовый файл в Excel...
Вроде бы все понятно, Array содержит массивы(2х1) - где первый элемент-номер столбца, а второй-формат. Но даже в макросе не срабатывает Array(1,3).
А такой вариант не устроит тебя?
Xls#=Create(0,Create:OLE)
Xls#{Prop:Create}='Excel.Application'
Xls#{'Application.Visible'}=True

Xls#{'Application.Workbooks.OpenText(Filename="D:\Test\5.txt",' &|
'StartRow=1, Origin=1251, DataType=1, TextQualifier=1, ConsecutiveDelimiter=False, Tab=True, Semicolon=False, Comma=False,' &|
'Space=False, Other=False, TrailingMinusNumbers=True, DataType=1)'} !отказываемся от Array-я

! ............
Xls#{'Application.Columns(2).NumberFormat'}='@' !второй столбец - текстовый
! ............
После двух часов раздумья понял, что это не то. Значение 9021-01-01 все крушит.
Всем пралитарское Спасибо и 'Желаю, чтобы ВСЕ !!!'
ABBASoft
Активист
Сообщения: 115
Зарегистрирован: 15 Май 2006, 18:08

Re: VB, OLE и Array.

Сообщение ABBASoft »

Уважаемые коллеги, использую OLE-объект Exel, читаю данные из Exel. Вопрос, как закрыть таблицу Exel или OLE-объект, т.к., таблицы все остаются открытыми. Cla8, 9759. С уважением, ABBAS.
kreator
✯ Ветеран ✯
Сообщения: 5037
Зарегистрирован: 28 Май 2009, 15:54
Откуда: Москва
Благодарил (а): 7 раз
Поблагодарили: 23 раза

Re: VB, OLE и Array.

Сообщение kreator »

Что-нибудь такое:

Код: Выделить всё

 ?Excel{'AppClose'}
 ?Excel{PROP:Deactivate}
We are hard at work… for you. :)
ABBASoft
Активист
Сообщения: 115
Зарегистрирован: 15 Май 2006, 18:08

Re: VB, OLE и Array.

Сообщение ABBASoft »

Пример взят из раздела нашего форума "Импорт данных из Excel в Сlarion". Там дан пример для Clarion 6.3, я перенес в 8-ку и все пекрасно работает (качаю данные из Exel). Но проблема та же: нельзя закрыть Exel. Как закрыть Exel (процесс)? Там в примере жалобы на эту же тему.
С уважением, ABBASoft.
ABBASoft
Активист
Сообщения: 115
Зарегистрирован: 15 Май 2006, 18:08

Re: VB, OLE и Array.

Сообщение ABBASoft »

Уважаемые коллеги, проблема решена! В примере из раздела "Импорт данных из Excel в Сlarion" Необходимо поставить оператор XlsFEQ('Application.Quit') перед XlsFEQ('PROP:Deactivate')=true (прочитал в Интернете - работа OLE-обьектами). Смотрите пример в разделе "Импорт данных из Excel в Сlarion".
Большое спасибо всем за помощь (особенно Kreator'у)!
С уважением, ABBASoft.
shu
Новичок
Сообщения: 6
Зарегистрирован: 16 Февраль 2013, 1:54

Re: VB, OLE и Array.

Сообщение shu »

kreator писал(а):Работаем с Excel через OLE. Нужно воспользоваться методом OpenText. У него есть аргумент типа Array(). Как это дело перевести в синтаксис Clarion'а?
Kreator, c методом OpenText разобрался? Поделись знаниями.
Как это странно, перевести серьезную тему до уровня сохранения из формата Excel в Clarion.
kreator
✯ Ветеран ✯
Сообщения: 5037
Зарегистрирован: 28 Май 2009, 15:54
Откуда: Москва
Благодарил (а): 7 раз
Поблагодарили: 23 раза

Re: VB, OLE и Array.

Сообщение kreator »

Не, не разобрался. Сделали через DBF. Правда, сам формат DBF - ограниченный, но для данной задачи прокатило. Ещё попробовали библиотеку Олега Руденко, рульная штука. Жаль времени нет сейчас для её изучения и перевода всех экспортов. Заметили пока одну проблему - xlsx не создаёт.
We are hard at work… for you. :)
Ответить