реклама на сайте
подробности

 
 
 
Reply to this topicStart new topic
> Работа с Exсel из приложения, написанного на C++Builder, Сохранение файла Exсel
kolisnichenko_r
сообщение May 5 2009, 12:06
Сообщение #1


Местный
***

Группа: Свой
Сообщений: 435
Регистрация: 12-09-07
Пользователь №: 30 482



Здравствуйте!
Разбираюсь с работой примера http://www.rxlib.ru/WinLesson/bles1.htm. После запуска программа работает нормально. Но мне не понятно в каком месте нужно указать путь для сохранения файла Exсel. По примеру, файл сохраняется в "Моих документах". А мне хочется в своем каталоге. Кто знает, направте в нужную стторону.
Go to the top of the page
 
+Quote Post
XVR
сообщение May 5 2009, 16:21
Сообщение #2


Гуру
******

Группа: Свой
Сообщений: 3 123
Регистрация: 7-04-07
Из: Химки
Пользователь №: 26 847



Вот в этой строке App.OlePropertyGet("WorkBooks",1).OleProcedure("SaveAs","MyTest"); вместо "MyTest" прописать имя файла с полным путем.
Go to the top of the page
 
+Quote Post
kolisnichenko_r
сообщение May 6 2009, 05:19
Сообщение #3


Местный
***

Группа: Свой
Сообщений: 435
Регистрация: 12-09-07
Пользователь №: 30 482



Цитата(XVR @ May 5 2009, 19:21) *
Вот в этой строке App.OlePropertyGet("WorkBooks",1).OleProcedure("SaveAs","MyTest"); вместо "MyTest" прописать имя файла с полным путем.

Спасибо!
Я за ночь еще чуть продвинулся:
сохранение в папке с проэктом (в любом удобном месте):
AnsiString sFile=GetCurrentDir()+"\\Mfile.xls";
App.OlePropertyGet("WorkBooks",1).OleProcedure("SaveAs",sFile.c_str());
Но появилось еще пару вопросов:
Как сделать, чтобы существующий файл заменялся без вопросов?
После завершения работы программы процесс Еxel не висел в системе?
Go to the top of the page
 
+Quote Post
XVR
сообщение May 6 2009, 07:28
Сообщение #4


Гуру
******

Группа: Свой
Сообщений: 3 123
Регистрация: 7-04-07
Из: Химки
Пользователь №: 26 847



Цитата(kolisnichenko_r @ May 6 2009, 09:19) *
Как сделать, чтобы существующий файл заменялся без вопросов?
Например предварительно стереть 'существующий файл'. Или подать соотвествующий параметр в SaveAs (их там много - смотри во встроенном help'е на VB в Excel'е)
Цитата
После завершения работы программы процесс Еxel не висел в системе?
Выполнить метод Quit - App.OleProcedure("Quit");
Go to the top of the page
 
+Quote Post
kolisnichenko_r
сообщение May 6 2009, 12:19
Сообщение #5


Местный
***

Группа: Свой
Сообщений: 435
Регистрация: 12-09-07
Пользователь №: 30 482



Цитата(XVR @ May 6 2009, 10:28) *
Например предварительно стереть 'существующий файл'. Или подать соотвествующий параметр в SaveAs (их там много - смотри во встроенном help'е на VB в Excel'е)
Выполнить метод Quit - App.OleProcedure("Quit");

А где этот хелп, что-то я не нашел.
Go to the top of the page
 
+Quote Post
XVR
сообщение May 7 2009, 08:33
Сообщение #6


Гуру
******

Группа: Свой
Сообщений: 3 123
Регистрация: 7-04-07
Из: Химки
Пользователь №: 26 847



Цитата(kolisnichenko_r @ May 6 2009, 16:19) *
А где этот хелп, что-то я не нашел.

По шагам (для Английской версии, для Русской названия пунктов меню будут русские):
  1. Запускаете Excel
  2. Меню: Tools->Macro->Visual Basic Editor (или Alt-F11)
  3. В открывшемся редакторе, меню: Help->Microsoft Visual Basic Help (или F1)
  4. В открывшейся панели (справа): Microsoft Excel Visual Basic Reference
  5. В нем: Methods->S->SaveAs method
  6. Выбираем: SaveAs method as it applies to the Workbook object.
  7. Читаем:
Цитата
SaveAs Method Saves changes to the workbook in a different file.

expression.SaveAs(FileName, FileFormat, Password, WriteResPassword, ReadOnlyRecommended, CreateBackup, AccessMode, ConflictResolution, AddToMru, TextCodepage, TextVisualLayout, Local)

expression Required. An expression that returns one of the above objects.

Filename Optional Variant. A string that indicates the name of the file to be saved. You can include a full path; if you don't, Microsoft Excel saves the file in the current folder.

FileFormat Optional Variant. The file format to use when you save the file. For a list of valid choices, see the FileFormat property. For an existing file, the default format is the last file format specified; for a new file, the default is the format of the version of Excel being used.

Password Optional Variant. A case-sensitive string (no more than 15 characters) that indicates the protection password to be given to the file.

WriteResPassword Optional Variant. A string that indicates the write-reservation password for this file. If a file is saved with the password and the password isn't supplied when the file is opened, the file is opened as read-only.

ReadOnlyRecommended Optional Variant. True to display a message when the file is opened, recommending that the file be opened as read-only.

CreateBackup Optional Variant. True to create a backup file.

AccessMode Optional XlSaveAsAccessMode.

XlSaveAsAccessMode can be one of these XlSaveAsAccessMode constants. xlExclusive (exclusive mode) xlNoChange default (don't change the access mode) xlShared (share list) If this argument is omitted, the access mode isn't changed. This argument is ignored if you save a shared list without changing the file name. To change the access mode, use the ExclusiveAccess method.

ConflictResolution Optional XlSaveConflictResolution.

XlSaveConflictResolution can be one of these XlSaveConflictResolution constants. xlUserResolution (display the conflict-resolution dialog box) xlLocalSessionChanges (automatically accept the local user's changes) xlOtherSessionChanges (accept other changes instead of the local user's changes) If this argument is omitted, the conflict-resolution dialog box is displayed.

AddToMru Optional Variant. True to add this workbook to the list of recently used files. The default value is False.

TextCodePage Optional Variant. Not used in U.S. English Microsoft Excel.

TextVisualLayout Optional Variant. Not used in U.S. English Microsoft Excel.

Local Optional Variant. True saves files against the language of Microsoft Excel (including control panel settings). False (default) saves files against the language of Visual Basic for Applications (VBA) (which is typically US English unless the VBA project where Workbooks.Open is run from is an old internationalized XL5/95 VBA project).
Go to the top of the page
 
+Quote Post
kolisnichenko_r
сообщение May 7 2009, 12:33
Сообщение #7


Местный
***

Группа: Свой
Сообщений: 435
Регистрация: 12-09-07
Пользователь №: 30 482



Записал так:
Код
App.OlePropertyGet("WorkBooks",1).OleProcedure("SaveAs",sFile.c_str(),xlUserResolution=0);

Комполируется, запускается, на когда доходит до сохранение выдает ошибку.
И еще во время инициализации Еxel на этот код выдает ошибку:
Код
//если Excel запущен - подключиться к нему
  try{
       App=Variant::GetActiveObject("Excel.Application");
      }

В чем проблема?
Go to the top of the page
 
+Quote Post
kolisnichenko_r
сообщение May 8 2009, 06:47
Сообщение #8


Местный
***

Группа: Свой
Сообщений: 435
Регистрация: 12-09-07
Пользователь №: 30 482



Пожалуйста, кто знает, разжуйте. Очень прошу. Сам не могу разобраться.
Go to the top of the page
 
+Quote Post
XVR
сообщение May 12 2009, 09:19
Сообщение #9


Гуру
******

Группа: Свой
Сообщений: 3 123
Регистрация: 7-04-07
Из: Химки
Пользователь №: 26 847



Цитата(kolisnichenko_r @ May 7 2009, 16:33) *
Записал так:
Код
App.OlePropertyGet("WorkBooks",1).OleProcedure("SaveAs",sFile.c_str(),xlUserResolution=0);
Странная запись. Вот это xlUserResolution=0 что такое? Если надо было задать параметр ConflictResolution то придется задавать и все параметры до него - OleProcedure не поддерживает передачу именованных параметров

Цитата
И еще во время инициализации Еxel на этот код выдает ошибку:
Код
//если Excel запущен - подключиться к нему
     try{
          App=Variant::GetActiveObject("Excel.Application");
         }

В чем проблема?

Какую ошибку?
Go to the top of the page
 
+Quote Post

Reply to this topicStart new topic
1 чел. читают эту тему (гостей: 1, скрытых пользователей: 0)
Пользователей: 0

 


RSS Текстовая версия Сейчас: 22nd June 2025 - 07:32
Рейтинг@Mail.ru


Страница сгенерированна за 0.01436 секунд с 7
ELECTRONIX ©2004-2016