Problema com C# a interagir com Microsoft Excel

MAdKulhas

Power Member
Boas tardes.

Hoje a programar para uma disciplina onde vamos Interacção de Aplicações, começamos hoje a dar a interoperabilidade com o Excel.

Na disciplina damos VB mas eu prefiro trabalhar em C# e estou com um problema a iniciar um novo documento em Excel. Coloco de seguida o meu código:

Código:
[SIZE=2][COLOR=#0000ff]using  [/COLOR][/SIZE][SIZE=2][COLOR=cyan]System;[/COLOR]
[/SIZE][SIZE=2][COLOR=#0000ff]using  [/COLOR][/SIZE][SIZE=2][COLOR=cyan]System.Collections.Generic;[/COLOR]
[/SIZE][SIZE=2][COLOR=#0000ff]using  [/COLOR][/SIZE][SIZE=2][COLOR=cyan]System.ComponentModel;[/COLOR]
[/SIZE][SIZE=2][COLOR=#0000ff]using  [/COLOR][/SIZE][SIZE=2][COLOR=cyan]System.Data;[/COLOR]
[/SIZE][SIZE=2][COLOR=#0000ff]using  [/COLOR][/SIZE][SIZE=2][COLOR=cyan]System.Drawing;[/COLOR]
[/SIZE][SIZE=2][COLOR=#0000ff]using  [/COLOR][/SIZE][SIZE=2][COLOR=cyan]System.Text;[/COLOR]
[/SIZE][SIZE=2][COLOR=#0000ff]using  [/COLOR][/SIZE][SIZE=2][COLOR=cyan]System.Windows.Forms;[/COLOR]
[/SIZE][SIZE=2][COLOR=#0000ff]using  [/COLOR][/SIZE][SIZE=2][COLOR=cyan]Excel;[/COLOR]
[/SIZE]
[SIZE=2][COLOR=#0000ff]namespace  [/COLOR][/SIZE][SIZE=2][COLOR=cyan]WindowsApplication1[/COLOR]
{
[/SIZE][SIZE=2][COLOR=#0000ff] public[/COLOR][/SIZE][SIZE=2][COLOR=#0000ff]partial[/COLOR][/SIZE][SIZE=2][COLOR=#0000ff]class  [/COLOR][/SIZE][SIZE=2][COLOR=#008080]WinExcel[/COLOR][/SIZE][SIZE=2] : [/SIZE][SIZE=2][COLOR=#008080]Form
[/COLOR][/SIZE][SIZE=2] {
[/SIZE][SIZE=2][COLOR=#0000ff]    private[/COLOR][/SIZE][SIZE=2] Excel.[/SIZE][SIZE=2][COLOR=#008080]Application[/COLOR][/SIZE][SIZE=2] excel;
 
[/SIZE][SIZE=2][COLOR=#0000ff]    public[/COLOR][/SIZE][SIZE=2] WinExcel()
      {
           InitializeComponent();
      }
[/SIZE]
[SIZE=2][COLOR=#0000ff]    private [/COLOR][/SIZE][SIZE=2][COLOR=#0000ff]void[/COLOR][/SIZE][SIZE=2] button1_Click([/SIZE][SIZE=2][COLOR=#0000ff]object[/COLOR][/SIZE][SIZE=2] sender, [/SIZE][SIZE=2][COLOR=#008080]EventArgs[/COLOR][/SIZE][SIZE=2] e)
      {
 
           excel = [/SIZE][SIZE=2][COLOR=#0000ff]new[/COLOR][/SIZE][SIZE=2] Excel.[/SIZE][SIZE=2][COLOR=#008080]Application[/COLOR][/SIZE][SIZE=2]();
           excel.Visible = [/SIZE][SIZE=2][COLOR=#0000ff]true[/COLOR][/SIZE][SIZE=2];
           Excel.[/SIZE][SIZE=2][COLOR=#008080]Workbook[/COLOR][/SIZE][SIZE=2] wrk = [/SIZE][SIZE=2][COLOR=#0000ff]new[/COLOR][/SIZE][SIZE=2][COLOR=#008080]Workbook[/COLOR][/SIZE][SIZE=2](); //ocorre uma excepção aqui nesta linha
 
           wrk = excel.Workbooks.Add([/SIZE][SIZE=2][COLOR=#0000ff]null[/COLOR][/SIZE][SIZE=2]);
           Excel.[/SIZE][SIZE=2][COLOR=#008080]Worksheet[/COLOR][/SIZE][SIZE=2] sheet = [/SIZE][SIZE=2][COLOR=#0000ff]new[/COLOR][/SIZE][SIZE=2] Excel.[/SIZE][SIZE=2][COLOR=#008080]Worksheet[/COLOR][/SIZE][SIZE=2]();
           sheet = (Excel.[/SIZE][SIZE=2][COLOR=#008080]Worksheet[/COLOR][/SIZE][SIZE=2])wrk.Worksheets[1];
           sheet.Columns[[/SIZE][SIZE=2][COLOR=#800000]"1"[/COLOR][/SIZE][SIZE=2], [/SIZE][SIZE=2][COLOR=#800000]"A"[/COLOR][/SIZE][SIZE=2]] = [/SIZE][SIZE=2][COLOR=#800000]"Ol "[/COLOR][/SIZE][SIZE=2];
           wrk.SaveAs([/SIZE][SIZE=2][COLOR=#800000]"C:\ficheiro.xls"[/COLOR][/SIZE][SIZE=2], [/SIZE][SIZE=2][COLOR=#800000]"xls"[/COLOR][/SIZE][SIZE=2], [/SIZE][SIZE=2][COLOR=#800000]""[/COLOR][/SIZE][SIZE=2], [/SIZE][SIZE=2][COLOR=#800000]""[/COLOR][/SIZE][SIZE=2], [/SIZE][SIZE=2][COLOR=#0000ff]null[/COLOR][/SIZE][SIZE=2], [/SIZE][SIZE=2][COLOR=#0000ff]null[/COLOR][/SIZE][SIZE=2], Excel.[/SIZE][SIZE=2][COLOR=#008080]XlSaveAsAccessMode[/COLOR][/SIZE][SIZE=2].xlNoChange, [/SIZE][SIZE=2][COLOR=#0000ff]null[/COLOR][/SIZE][SIZE=2], [/SIZE][SIZE=2][COLOR=#0000ff]null[/COLOR][/SIZE][SIZE=2], [/SIZE][SIZE=2][COLOR=#0000ff]null[/COLOR][/SIZE][SIZE=2], [/SIZE][SIZE=2][COLOR=#0000ff]null[/COLOR][/SIZE][SIZE=2], [/SIZE][SIZE=2][COLOR=#0000ff]null[/COLOR][/SIZE][SIZE=2]);
           wrk.Close([/SIZE][SIZE=2][COLOR=#0000ff]null[/COLOR][/SIZE][SIZE=2], [/SIZE][SIZE=2][COLOR=#0000ff]null[/COLOR][/SIZE][SIZE=2], [/SIZE][SIZE=2][COLOR=#0000ff]null[/COLOR][/SIZE][SIZE=2]);
           excel.Quit();
           System.Runtime.InteropServices.[/SIZE][SIZE=2][COLOR=#008080]Marshal[/COLOR][/SIZE][SIZE=2].ReleaseComObject(sheet);
           System.Runtime.InteropServices.[/SIZE][SIZE=2][COLOR=#008080]Marshal[/COLOR][/SIZE][SIZE=2].ReleaseComObject(wrk);
 
      }
   }
}
[/SIZE]


Não sei também se estou a fazer da melhor maneira, mas gostaria de saber a vossa opinião e como resolver o facto de estar ali a aparecer uma excepção estranha, visto que até já adicionei as referências ao Excel.

Cumprimentos.
 
Põe a mensagem da excepção, pode ser que ajude...

EDIT: e esta linha: "wrk = excel.Workbooks.Add(null);" não me parece muito bem... talvez seja antes "excel.Workbooks.Add(wrk);"
 
Última edição:
Aqui vai o que copiei da excepção que ocorreu:

Código:
System.Runtime.InteropServices.COMException was unhandled
  Message="Retrieving the COM class factory for component with CLSID {00020819-0000-0000-C000-000000000046} failed due to the following error: 80040154."
  Source="WindowsApplication1"
  ErrorCode=-2147221164
  StackTrace:
       at WindowsApplication1.WinExcel.button1_Click(Object sender, EventArgs e) in C:\Documents and Settings\M@dKulhas\Os meus documentos\Visual Studio 2005\Projects\sln_ficha_6\sln_ficha_6\WindowsApplication1\Form1.cs:line 27
       at System.Windows.Forms.Control.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
       at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ButtonBase.WndProc(Message& m)
       at System.Windows.Forms.Button.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.Run(Form mainForm)
       at WindowsApplication1.Program.Main() in C:\Documents and Settings\M@dKulhas\Os meus documentos\Visual Studio 2005\Projects\sln_ficha_6\sln_ficha_6\WindowsApplication1\Program.cs:line 17
       at System.AppDomain.nExecuteAssembly(Assembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
 
Bem eu não sou assim tão estúpido :lol:

Sim, ele chega até a executar o programa em background mas quando vou a criar um novo documento dentro dele, simplesmente aparece-me essa excepção.
 
MAdKulhas disse:
Bem eu não sou assim tão estúpido :lol:

Sim, ele chega até a executar o programa em background mas quando vou a criar um novo documento dentro dele, simplesmente aparece-me essa excepção.

Código:
Microsoft.Office.Interop.Excel.Workbook wrk= 
				excel.Workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);

em vez de

Código:
Excel.Workbook wrk = newWorkbook(); //ocorre uma excepção aqui nesta linha
wrk = excel.Workbooks.Add(null);
 
nao tem nada de estranho. eu uso o vs 2003.
os namespaces devem mudar.

deve ser o Excel.XlWBATemplate.xlWBATWorksheet .

Excel.Workbook wrk= excel.Workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);

/ing
 
Back
Topo