Форум программистов, компьютерный форум, киберфорум
С++ для начинающих
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.76/68: Рейтинг темы: голосов - 68, средняя оценка - 4.76
0 / 0 / 0
Регистрация: 13.05.2014
Сообщений: 4

C++ и Excel

16.03.2008, 22:14. Показов 14056. Ответов 2
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Начну с задачи:

Есть 5 Excel файлов в каждом по 60 листов на каждом листе занято определенное количество строк.
Необходимо скопировать в 6-ой Excel файл данные из 1-й файл 3 лист с 5-7 строку
3-й файл 7 лист с 9-20 строку
5-й файл 9 лист с 3-12 строку

Помогите найти информацию или исходник
Заранее Благодарен
0
Лучшие ответы (1)
cpp_developer
Эксперт
20123 / 5690 / 1417
Регистрация: 09.04.2010
Сообщений: 22,546
Блог
16.03.2008, 22:14
Ответы с готовыми решениями:

Скопировать один лист из одной книги excel в другую книгу excel
Мне нужно скопировать 1 лист из одной книги excel в другую книгу excel. Именно лист, а не диапазон ячеек. Диапазон ячеек я нашёл тут...

Матлаб выводит в excel число, а excel отображает его как дату
Здравствуйте, вот кусок кода. Ну проблемма вся в заголовке. str = {'Передаточное число третьей передачи равно ',num2str(i3)}; ...

Программа AtteStat1205 для Excel, встраивает модули в Excel, как ее удалить
Скачал удивительную программу AtteStat1205 интересные методы, все круто расписано. но не могу удалить ...

2
Гость1234567890
18.03.2008, 05:57
Лучший ответ Сообщение было отмечено как решение

Решение

HOWTO: Automate Excel 97/2000 and Then Know the User Closed It

Q192348


--------------------------------------------------------------------------------
The information in this article applies to:

Microsoft Visual Studio 97
Microsoft Visual C++, 32-bit Editions, versions 5.0, 6.0
Microsoft Office 2000 Developer
Microsoft Excel 2000
Microsoft Excel 97 for Windows
The Microsoft Foundation Classes (MFC)

--------------------------------------------------------------------------------


SUMMARY
This article illustrates how to:

Automate Microsoft Excel 97 or Excel 2000 using Microsoft Visual C++ and Microsoft Foundation Classes (MFC).


Wait for the end-user to close that instance of Excel.


Have your VC++ controller know that Excel is closed.





MORE INFORMATION
Microsoft Excel 97 or Excel 2000 do not raise a "Quit" event that can observed by other processes. When an out-of-process application that controls an instance of Excel releases all object references to the instance and tells it to quit, that controller knows Excel has terminated. But, when the controller creates and makes an instance of Excel visible it does not know when the end-user has closed Excel. As long as the controlling application has unreleased object references to the instance, Excel remains loaded and registered in the Running Object Table.

This article uses the concepts of Microsoft Knowledge Base article:



Q178749 HOWTO: Create Automation Project Using MFC and a Type Library
and modifies that article's step 14 to include sample code to illustrate one method of determining that the end-user has actually closed the instance of Excel. The approach is to call WaitForSingleObject() to determine that the specific Excel process has terminated.
Notes for Automating Microsoft Excel 2000
Some methods and properties have changed for Microsoft Excel 2000. For additional information about using the sample code described in this article with the Microsoft Excel 2000 type library, please see the following article in the Microsoft Knowledge Base:


Q224925 INFO: Type Libraries for Office 2000 Have Changed
Create an Automation Project
With Microsoft Developer Studio, start a new "MFC AppWizard (exe)" project named AutoProject.


In step 1 of the MFC AppWizard, choose Dialog Based for the application type and click Finish. The New Project Information dialog box appears and indicates that the Classes to be created include:

Application: CAutoProjectApp in AutoProject.h and AutoProject.cpp
Dialog: CAutoProjectDlg in AutoProject.h and AutoProjectDlg.cpp

Click OK to create the project.


In the project workspace, click the "Resource View" tab. Double-click AutoProject Resources to expand the resource tree. Double-click Dialog in the Resource tree and double-click to select the dialog box resource IDD_AUTOPROJECT_DIALOG.


Remove the Label control (IDC_STATIC).


Change the name of the OK button to IDSEEXLQUIT and the caption to "See Excel Quit." Close the AutoProject.rc dialog box design form.


Click ClassWizard on the View menu (or press CTRL+W).


Select the Message Maps tab. Select IDSEEXLQUIT in the Object Ids list box and select BN_CLICKED in the Messages list box. Click Add Function and accept the function name OnSeexlquit. Click OK to close the ClassWizard.

NOTE: This step adds a declaration for the function member OnSeexlquit(); to the header file named AutoProjectDLG.h. This step also adds an empty skeleton message handler function named CAutoProjectDlg::OnSeexlquit() to the file named AutoProjectDLG.cpp.


Click ClassWizard on the View menu (or press CTRL+W).


Select the Automation tab. Click Add Class and choose "From a type library." Navigate to select the object library for Microsoft Excel 8.0 Object Library; (the default location is C:\Program Files\Microsoft Office\Office\Excel8.olb) and click Open. Select all classes in the Confirm Classes list and click OK. For Excel 2000, select the object library for Microsoft Excel 9.0 Object Library; The default location is C:\Program Files\Microsoft Office\Office\Excel9.ol.

NOTE: The list box in the Confirm Classes dialog box contains all of the IDispatch interfaces in the Microsoft Excel type library. In the lower half of the dialog box you will see that an Implementation file named Excel8.cpp contains generated class wrappers derived from ColeDispatchDriver(), and the appropriate declaration header file is named Excel8.h. For Excel 2000, the implementation file is Excel9.cpp and the declaration header file is Excel9.h.


Click OK to close the MFC ClassWizard dialog box.


Add the following code to the CAutoProjectApp::InitInstance() function, which loads and enables the COM services library:
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
      BOOL CAutoProjectApp::InitInstance()
      {
         if(!AfxOleInit())  // Your addition starts here.
         {
            AfxMessageBox("Could not initialize COM dll");
            return FALSE;
         }                 // End of your addition.
 
         AfxEnableControlContainer();
      .
      .
      .
 
      }


Add the following line to the #include statements at the top of the AutoProject.cpp program file:

C++
1
      #include <afxdisp.h>


Add the include statement for Excel8.h after the include statement for Stdafx.h at the top of the AutoProjectDlg.cpp program file:

C++
1
2
3
      #include "stdafx.h"
      #include "excel8.h"
      // for Excel 2000, use #include "excel9.h"


Add automation code to the CAutoProjectDlg::OnSeexlquit() so that it appears as shown below:

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
      void CAutoProjectDlg::OnSeexlquit() // Message handler function.
      {
       char buf[1024];  // General purpose message buffer.
       _Application oExcel;  // oExcel is an _Application object.
       Workbooks oBooks;
       LPDISPATCH lpDisp;
 
      // Common OLE-variants... Easy variants to use for calling arguments.
      COleVariant
                 covTrue((short)TRUE),
                 covFalse((short)FALSE),
                 covOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR);
 
      // Start Excel and get Application object.
      if(!oExcel.CreateDispatch("Excel.Application"))
      {
       AfxMessageBox("Couldn't CreateDispatch on Excel");
       return;
      }
 
      // Set visible.
      oExcel.SetVisible(TRUE);
      oExcel.SetUserControl(TRUE);  // This is a property of the
                                    //  _Application object. Set it so you
                                    //  can Release the oExcel and
                                    //  oBooks objects without killing
                                    //  Excel.
 
      // Get Workbooks collection...
      lpDisp = oExcel.GetWorkbooks();  // Get an IDispatch pointer
      ASSERT(lpDisp);            //   or fail.
      oBooks.AttachDispatch( lpDisp );  // Attach IDispatch pointer to
                                        //  oBooks object.
 
      // Open a workbook...
      lpDisp = oBooks.Open("C:\\Mybook.xls",  // Change for your .xls.
           covOptional, covOptional, covOptional, covOptional,
           covOptional, covOptional, covOptional, covOptional,
           covOptional, covOptional, covOptional, covOptional
           );
 
      ASSERT(lpDisp);  // It better have worked?
 
      HWND hWnd;
      hWnd = ::FindWindow("XLMain",  // Pointer to class name.
                           NULL   // Pointer to window name option.
                           );
      if(NULL==hWnd)
      {
       long lErr = GetLastError();
       sprintf(buf, "FindWindow error code = %d", lErr);
       AfxMessageBox(buf);
      }
 
      DWORD pid;  // Variable to hold the process ID.
      DWORD dThread;  // Variable to hold (unused) thread ID.
      dThread =  GetWindowThreadProcessId(hWnd, // Handle to window.
                                          &amp;pid  //  Address of variable
                                                //  for process identifier.
                                          );
      HANDLE hProcess; // Handle to existing process
 
      hProcess = OpenProcess(SYNCHRONIZE | PROCESS_ALL_ACCESS,  // access
                                                                //  flag
                             TRUE,  // handle inheritance flag
                             pid  // process identifier
                             );
 
      oBooks.ReleaseDispatch();  // Release the object-IDispatch binding.
      oExcel.ReleaseDispatch();
      oBooks = NULL;  // Destroy the object references.
      oExcel = NULL;
 
      DWORD  dwReason;  // Variable to receive signal.
 
      dwReason = WaitForSingleObject(hProcess,  // Handle to object to
                                                //  wait for its end.
                                     INFINITE   // Time-out interval in
                                                //  milliseconds.
                                     );
 
      sprintf(buf, "Reason for Wait to terminate is %d", dwReason);
                                                        // Zero is good.
      AfxMessageBox(buf);
     }


Build and run the project. When the dialog box appears, minimize Visual Studio, leaving the dialog box from your project. Click the "See Excel Quit" button. Wait for Excel to appear and be visible. Once it is visible, at your leisure, click the control button at the right end of the title bar (the "X") to close Excel.
Успехов!
0 / 0 / 0
Регистрация: 24.06.2011
Сообщений: 15
17.10.2011, 18:30
Схожий вопрос. Каким образом можно записать какие-то данные в ячейку Excel.
Я так понял это делается как вариант с помощью COM объектов самого Экселя.
Может кто-то поможет, показав пример, как создать с помощью С такой объект, и записать в него какое-то значение, и какие доп. библиотеки при этом надо подключать.

Инструменты: VisualStudio 2010, Excel 2010.

Заранее очень большое спасибо!!!!
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
raxper
Эксперт
30234 / 6612 / 1498
Регистрация: 28.12.2010
Сообщений: 21,154
Блог
17.10.2011, 18:30
Помогаю со студенческими работами здесь

Макрос для переноса данных из одного Excel в другой Excel файл
Уважаемые эксперты, очень нужна ваша помощь! Подскажите, пожалуйста, как прописать макрос, который переносит данные из одного excel файла в...

Access - Excel, код не воспринимает количество строк в Excel более 65000
Добрый день! Есть БД (Access), есть файл Excel, где происходит обработка данных. Код ниже работает отлично, НО он не воспринимает...

Какие Excel библиотеки необходимы для создания CreateObject('Excel.Application') ?
проблема в том что клиент не хочет пользоваться MS Excel. существуют ли возможность работы с Open Office, Star Office, MS Works. или может...

Microsoft.Office.Interop.Excel.Application процессы Excel в памяти компьютера
Добрый день, коллеги! Программа работает с файлами Excel. В каждой процедуре я указываю, что приложение должно быть не видимым...

Возможно ли использование Variant Excel, Book, Sheet без установленного Excel?
Можно ли сделать как написано в названии?


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
3
Ответ Создать тему
Новые блоги и статьи
Музыка, написанная Искусственным Интеллектом
volvo 04.12.2025
Всем привет. Некоторое время назад меня заинтересовало, что уже умеет ИИ в плане написания музыки для песен, и, собственно, исполнения этих самых песен. Стихов у нас много, уже вышли 4 книги, еще 3. . .
От async/await к виртуальным потокам в Python
IndentationError 23.11.2025
Армин Ронахер поставил под сомнение async/ await. Создатель Flask заявляет: цветные функции - провал, виртуальные потоки - решение. Не threading-динозавры, а новое поколение лёгких потоков. Откат?. . .
Поиск "дружественных имён" СОМ портов
Argus19 22.11.2025
Поиск "дружественных имён" СОМ портов На странице: https:/ / norseev. ru/ 2018/ 01/ 04/ comportlist_windows/ нашёл схожую тему. Там приведён код на С++, который показывает только имена СОМ портов, типа,. . .
Сколько Государство потратило денег на меня, обеспечивая инсулином.
Programma_Boinc 20.11.2025
Сколько Государство потратило денег на меня, обеспечивая инсулином. Вот решила сделать интересный приблизительный подсчет, сколько государство потратило на меня денег на покупку инсулинов. . . .
Ломающие изменения в C#.NStar Alpha
Etyuhibosecyu 20.11.2025
Уже можно не только тестировать, но и пользоваться C#. NStar - писать оконные приложения, содержащие надписи, кнопки, текстовые поля и даже изображения, например, моя игра "Три в ряд" написана на этом. . .
Мысли в слух
kumehtar 18.11.2025
Кстати, совсем недавно имел разговор на тему медитаций с людьми. И обнаружил, что они вообще не понимают что такое медитация и зачем она нужна. Самые базовые вещи. Для них это - когда просто люди. . .
Создание Single Page Application на фреймах
krapotkin 16.11.2025
Статья исключительно для начинающих. Подходы оригинальностью не блещут. В век Веб все очень привыкли к дизайну Single-Page-Application . Быстренько разберем подход "на фреймах". Мы делаем одну. . .
Фото: Daniel Greenwood
kumehtar 13.11.2025
Расскажи мне о Мире, бродяга
kumehtar 12.11.2025
— Расскажи мне о Мире, бродяга, Ты же видел моря и метели. Как сменялись короны и стяги, Как эпохи стрелою летели. - Этот мир — это крылья и горы, Снег и пламя, любовь и тревоги, И бескрайние. . .
PowerShell Snippets
iNNOKENTIY21 11.11.2025
Модуль PowerShell 5. 1+ : Snippets. psm1 У меня модуль расположен в пользовательской папке модулей, по умолчанию: \Documents\WindowsPowerShell\Modules\Snippets\ А в самом низу файла-профиля. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2025, CyberForum.ru