powered by simpleCommunicator - 2.0.57     © 2025 Programmizd 02
Целевая тема:
Создать новую тему:
Автор:
Закрыть
Цитировать
Форумы / WinForms, .Net Framework [игнор отключен] [закрыт для гостей] / Открыть открыть файл excel в control WebBrowser
6 сообщений из 6, страница 1 из 1
Открыть открыть файл excel в control WebBrowser
    #38165888
qwerty5000
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Доброго времени суток!

Хочу открыть Excel внутри приложения.....прочитал кучу примеров....написал код в результате Excel открывается отдельным файлом не в control-e WebBrowser(((. Код ниже по тексту. Есть подозрение что надо явно связывать Excel.Application и WebBrowser...
Подскажите кто знает в чем может быть трабл, уж очень надо.


Код: 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.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
105.
106.
107.
108.
109.
110.
111.
112.
113.
114.
115.
116.
117.
118.
119.
120.
121.
122.
123.
124.
125.
126.
127.
128.
129.
130.
131.
132.
133.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Office.Core;
using Microsoft.Office;
using System.Reflection;
using SHDocVw;
using Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using Office = Microsoft.Office.Core;

namespace ASODU_manual_input
{
    public partial class Form1 : Form
    {
        private string m_ExcelFileName = "test.xls";
        private Microsoft.Office.Interop.Excel.Application m_XlApplication=null;
        private Office.CommandBar m_StandardCommandBar = null;
        private Workbook m_Workbook = null;
        [DllImport("ole32.dll")]
        static extern int GetRunningObjectTable
            (uint reserved, out IRunningObjectTable pprot);
        [DllImport("ole32.dll")]
        static extern int CreateBindCtx(uint reserved, out IBindCtx pctx);

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (this.openFileDialog1.ShowDialog() == DialogResult.Cancel) return;
            m_ExcelFileName = getFileName(this.openFileDialog1.FileName);
            this.OpenFile(this.openFileDialog1.FileName);
        }

        public String getFileName(String path)
        {
            string[] splitpath = path.Split('\\'); 
            string name = splitpath[splitpath.Length - 1];
            return name;
        }

        public void OpenFile(string filename)
        {
            if (!System.IO.File.Exists(filename)) throw new Exception();
            this.webBrowser1.Navigate(filename, false);
            
        }

        private void webBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e)
        {
            // Creation of the workbook object
            if ((m_Workbook = RetrieveWorkbook(m_ExcelFileName)) == null) return;
            // Create the Excel.Application
            m_XlApplication = (Microsoft.Office.Interop.Excel.Application)m_Workbook.Application;
            AttachApplication();
          }

        private void AttachApplication()
        {
            try
            {
                // Creation of the standard toolbar
                m_StandardCommandBar = m_XlApplication.CommandBars["Standard"];
                m_StandardCommandBar.Position = Office.MsoBarPosition.msoBarTop;
                m_StandardCommandBar.Visible = true;
                // Enable the OpenFile and New buttons
                foreach (Office.CommandBarControl control in m_StandardCommandBar.Controls)
                {
                    string name = control.get_accName(Missing.Value);
                    if (name.Equals("Nouveau")) ((Office.CommandBarButton)control).Enabled = false;
                    if (name.Equals("Ouvrir")) ((Office.CommandBarButton)control).Enabled = false;
                }
            }
            catch
            {
                MessageBox.Show("Impossible de charger le fichier Excel");
                return;
            }
        }

        public Workbook RetrieveWorkbook(string xlfile)
        {
            IRunningObjectTable prot = null;
            IEnumMoniker pmonkenum = null;
            try
            {
                IntPtr pfetched = IntPtr.Zero;
                // Query the running object table (ROT)
                if (GetRunningObjectTable(0, out prot) != 0 || prot == null) return null;
                prot.EnumRunning(out pmonkenum); pmonkenum.Reset();
                IMoniker[] monikers = new IMoniker[1];
                while (pmonkenum.Next(1, monikers, pfetched) == 0)
                {
                    IBindCtx pctx; string filepathname;
                    CreateBindCtx(0, out pctx);
                    // Get the name of the file
                    monikers[0].GetDisplayName(pctx, null, out filepathname);
                    // Clean up
                    Marshal.ReleaseComObject(pctx);
                    // Search for the workbook
                    if (filepathname.IndexOf(xlfile) != -1)
                    {
                        object roval;
                        // Get a handle on the workbook
                        prot.GetObject(monikers[0], out roval);
                        return roval as Workbook;
                    }
                }
            }
            catch
            {
                return null;
            }
            finally
            {
                // Clean up
                if (prot != null) Marshal.ReleaseComObject(prot);
                if (pmonkenum != null) Marshal.ReleaseComObject(pmonkenum);
            }
            return null;
        }
    }
}
...
Рейтинг: 0 / 0
Открыть открыть файл excel в control WebBrowser
    #38166217
sld
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
sld
Гость
непонятно нахрена это нужно конешно.
а в простом браузере ты можешь открыть excel файл?
...
Рейтинг: 0 / 0
Открыть открыть файл excel в control WebBrowser
    #38166235
SerP1983
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
...
Рейтинг: 0 / 0
Открыть открыть файл excel в control WebBrowser
    #38166606
qwerty5000
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
SerP1983,

Спасибо! По ссылке приведена информация в обратном направлении (настройка файлов office для открытия в соответствующих программах вне браузера ИЕ).

В семерке же вкладка тип файлов из Свойство папок пропала.....????????????
...
Рейтинг: 0 / 0
Открыть открыть файл excel в control WebBrowser
    #38166614
qwerty5000
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
sld,

перетаскивую xls в браузер - файл открывается вне браузера!!!
...
Рейтинг: 0 / 0
Открыть открыть файл excel в control WebBrowser
    #38166629
qwerty5000
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
может сторонняя прожка есть которая позволяет настраивать подобные вещи в 7
...
Рейтинг: 0 / 0
6 сообщений из 6, страница 1 из 1
Форумы / WinForms, .Net Framework [игнор отключен] [закрыт для гостей] / Открыть открыть файл excel в control WebBrowser
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]