Hallo,
mein Problem ist folgendes: Ich sammle aus der Datenbank Daten zusammen und gebe diese auf dem Bildschirm aus. Des weiteren wird die Option geboten, diese Informationen in einem Word-File zu exportieren.
Ich habe bereits eine bestehende WordVorlage wo ich nun reinschreiben möchte. Die Frage ist wie geht das. Ein neues WordDoc zu öffnen ist kein Problem.
Aber ich tue mich damit schwer:
a) meine Word Vorlage überhaupt zu öffnen
b) in folge dessen die Textmarken auszuwählen und dann da rein zuschreiben
c) Wie ist es möglich ein Standard-Format (á la Überschrift 1, Überschrift 2) in das Dokument einzu binden.
Mein bisheriger Code basiert momentan auf der Microsoft Online Hilfe. Die ich allerdings schlecht kommentiert finde:
class WordAppMain
{
static object missing = Missing.Value;
static object missing2 = Missing.Value;
static object missing3 = Missing.Value;
static object missing4 = Missing.Value;
static object missing5 = Missing.Value;
static object missing6 = Missing.Value;
static object missing7 = Missing.Value;
static object missing8 = Missing.Value;
static object missing9 = Missing.Value;
static object missing10 = Missing.Value;
static object missing11 = Missing.Value;
static object missing12 = Missing.Value;
static object missing13 = Missing.Value;
static int Main()
{
WordAppMain myWord = new WordAppMain();
int return_Result = 0;
// Create a word object that we can manipulate
Application Word_App = null;
Document Word_doc=null;
try
{
Word_App = new Application();
Word_doc=new Document();
}
catch(Exception e)
{
Console.WriteLine("Can't create a word document " + e.ToString());
return_Result = 1;
goto Exit;
}
AutoCorrect autocorrect = Word_App.AutoCorrect;
AutoCorrectEntries autoEntries = autocorrect.Entries;
string theEnd= "\nThe End";
autoEntries.Add("Inntroduction", "Introduction");
Documents Docs = Word_App.Documents;
if (Docs == null)
{
Console.WriteLine("Docs is null");
}
else
{
Console.WriteLine("Docs exists:" + Docs.Count);
}
Word_App.Visible=true;
_Document my_Doc= (_Document) Word_doc;
Word_doc=Docs.Add(ref missing, ref missing, ref missing, ref missing);
object start = 0;
object end = 0;
Range range = Word_doc.Range(ref missing,ref missing);
// add text to the doc -- this contains some deliberate misspellings so that we can correct them in a short while
range.Text="Microsoft Word Interoperability Sample\n\nInntroduction:\n\nMicrosoft .NET will allow the creation of truly distributed XML Web services. These services will integrate and collaborate with a range of complementary services to work for customers in ways that today's internet companies can only dream of. Microsoft .NET will drive the Next Generation Internet and will shift the focus from individual Web sites or devices connected to the Internet, to constellations of computers, devices, and services that work together to deliver broader, richer solutions.\nFor more info go to:\n ";
// Wait so the starting state can be admired
Thread.Sleep(2000);
// Format the title
Font fc= new Font();
try
{
Console.WriteLine("Formatting the title");
start = 0; end = 40;
range=Word_doc.Range(ref start, ref end);
range.Font.Size=24;
range.Font.Bold=1;
range.Font.Color=WdColor.wdColorGray30;
start = 40; end = 54;
range=Word_doc.Range(ref start, ref end);
range.Font.Size=14;
}
catch(Exception e)
{
Console.WriteLine(" Font exception:{0}", e.ToString());
}
// Wait so the new formatting can be appreciated
Thread.Sleep(3000);
autocorrect.ReplaceTextFromSpellingChecker=true;
// Fix inntroduction
string obj = "Introduction";
AutoCorrectEntry errEntry= autoEntries.Add("Inntroduction", obj);
Words myWords=Word_doc.Words;
Range errRange= myWords[7];
errEntry.Apply(errRange);
// Add a caption to the window and get it back
Window myWindow = Word_App.ActiveWindow;
myWindow.Caption = "Managed Word execution from C# ";
string gotCaption = myWindow.Caption;
if (gotCaption.Equals("Managed Word execution from C# "))
{
Console.WriteLine("Caption assigned and got back");
return_Result = 1;
}
Thread.Sleep(2000);
// define the selection object, find and replace text
Selection mySelection = myWindow.Selection;
try
{
start = 65; end = 69;
range=Word_doc.Range(ref start, ref end);
Console.WriteLine("The color of .NET is being changed");
range.Font.Bold=16;
range.Font.Color=WdColor.wdColorLavender;
}
catch(Exception e)
{
Console.WriteLine(" Font exception:{0}", e.ToString());
}
Thread.Sleep(2000);
// underline the selected text
range=Word_doc.Range(ref start,ref end);
range.Underline=(WdUnderline.wdUnderlineDouble);
// add hyperlink and follow the hyperlink
Hyperlinks my_Hyperlinks = Word_doc.Hyperlinks;
// Make the range past the end of all document text
mySelection.Start = 9999;
mySelection.End = 9999;
range = mySelection.Range;
// Add a hyperlink
string myAddress = "http://go.microsoft.com/fwlink/?linkid=3269&clcid=0x409";
object obj_Address = myAddress;
Console.WriteLine("Adding hyperlink to the document");
Hyperlink my_Hyperlink1= my_Hyperlinks._Add(range, ref obj_Address, ref missing);
Word_App.ActiveWindow.Selection.InsertAfter("\n");
Thread.Sleep(5000);
// Open a window to Hyperlink
Process ie = Process.Start("iexplore.exe", my_Hyperlink1.Address);
// Wait for a short spell to allow the page to be examined
Thread.Sleep(10000);
// close the browser first
Console.WriteLine("Removing browser window");
ie.Kill();
// Display "The End"
Word_App.ActiveWindow.Selection.InsertAfter(theEnd);
Word_App.ActiveWindow.Selection.Start = 0;
Word_App.ActiveWindow.Selection.End = 0;
Word_App.Activate();
Thread.Sleep(5000);
// Close Microsoft Word
object myBool = WdSaveOptions.wdDoNotSaveChanges;
Word_App.ActiveWindow.Close(ref myBool,ref missing);
Exit:
return return_Result;
}
}
Kann mir jemand helfen?
Es ist nur der ein Superheld, der sich selbst für Super hält
Du kannst den Word-Makro-Recorder verwenden, um rauszufinden, wie man eine Vorlage lädt und zu bestimmten Textmarken springt. Das erzeugte Makro musst Du dann nur in C# umsetzen (Der Makro-Recorder schreibt leider nur VBA-Makros).
So einfach wie möglich, aber nicht einfacher. [Albert Einstein]
take a look at
* baer-torsten.de
* codinghints
Das mit den Missings hat mich auch verwundert. Und warum werden die sogar klassenweit deklariert? Das verstehe ich nicht.
_Original von Rainbird_Und warum werden die sogar klassenweit deklariert? Das verstehe ich nicht. Weil man nicht aus einer statischen Methode auf Instanzenmember zugreifen kann 😉
Für das nicht statische Feld, die Methode oder die Eigenschaft "..." ist ein Objektverweis erforderlich.
So einfach wie möglich, aber nicht einfacher. [Albert Einstein]
take a look at
* baer-torsten.de
* codinghints
Ich hätte die lokal innerhalb der statischen Methode deklariert. Das hab ich gemeint.
Also ich bin mittlerweile soweit öffne meine gewünschte WordDatei, kann normalen Text hineinschreiben, aber wie kannich diesen Text 'a la Überschrift 1, Überschrift 2 formatieren?
Textmarken werden mir wohl nicht viel bringen, wenn ich den Text aus einer Datenbank auslese und immer unterschiedlich viele Überschriften 1 gefolgt von einem Standardtext vorkommen oder?
Würde mich über hilfe freuen.
Momentan ist es so gelöst - Eine Methode um die Word Datei zu öffnen,
Eine Methode um den Dokumententitel zu erstellen
Eine Methode um in die Datei zu schreiben.
Und hier möchte ich nun Formatieren a la:
public void Write WordText(String sZuSchreibenderText, string Formatvorlage)
{
try
{
Word_doc.Range.Text = zuSchreibenderText;
}
catch (Exception e)
{
Console.WriteLine("Kann nicht in Word-Dokument schreiben" + e.ToString());
}
}
Also habe den Code gerade abstrahiert nö 😉
Es ist nur der ein Superheld, der sich selbst für Super hält
Wenn ich richtig gesehen hab is das, was du suchst
Microsoft.Office.Interop.Word.Range.ParagraphFormat.Style
und
Microsoft.Office.Interop.Word.WdBuiltinStyle.wdStyleHeading1;
Grüße
So einfach wie möglich, aber nicht einfacher. [Albert Einstein]
take a look at
* baer-torsten.de
* codinghints
Sodele ich bin nun einen großen Schritt weiter 🙂 Aber nicht fertig.
Ich kann nun:
Was ich nicht kann ist, den Text den ich reinschreibe wird in einer While-Schleife die ein DataRow Object ausliest generiert.
Ich Schreibe über ein BookMark in Word rein, Mein Problem ist, dass wenn er in Word schreibt schreibt er 1 dann schreibt er 2 dann Schreibt er 3
Im Word steht später
3
2
1
Ich will aber dass das in umgekehrter Reihenfolge dasteht sprich er soll immer unter dem eingefügtem Text schreiben nicht darunter. Ist dann das reinschreiben über eine Textmarke überhaupt das richtige?
Des weiteren kann ich nun formatieren wie 'el toro geraten hat. Funktioniert temporär spitze. Das Problem ist, ich füge mehrere Seiten Text ein. Und er formatiert immer den gesamten Text. Wie mache ich das, dass er auch immer nur den Text formatiert, den er gerade einfügt?
Würde mich mal wieder riesig über fachkundige Hilfe von euch freuen.
Zum stöbern habe ich da mal ein bisschen Programmcode von mir
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Threading;
using Microsoft.Office.Interop.Word;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Reflection;
using System.Collections;
namespace Schuler.ChangeLog.Data
{
public class FuncExportWord
{
#region Members
private object missing = Missing.Value;
private Application Word_App = new Application();
private Document Word_doc = new Document();
//--------------------------------------
//Wordspezifische Objekte
//--------------------------------------
private object oBookMark = "NeuerungenText";
private object oU1 = WdBuiltinStyle.wdStyleHeading1;
private object oU2 = WdBuiltinStyle.wdStyleHeading2;
private object oU3 = WdBuiltinStyle.wdStyleHeading3;
private object oStyleText = WdBuiltinStyle.wdStyleBodyText;
private object oNewLine = WdBreakType.wdLineBreak;
//--------------------------------------
#region Methods
// Hier sind noch mehr Methoden ;)
public void WriteWordText(string TextWert, object Format, object oBookMark)
{
//Word_doc.Bookmarks.get_Item(ref oBookMark).st
//Range.ParagraphFormat.Style;
//WdBuiltinStyle.wdStyleHeading2;
Word_doc.Bookmarks.get_Item(ref oBookMark).Range.Text = TextWert;
//Neue Textmarke generieren
string Textmarke = sTextMarkName + " " + iTextMarkNo.ToString();
object oRange = Word_App.Selection.Range;
//Word_doc.Bookmarks.Add(Textmarke, ref oRange);
// So wie mache ich das hier richtig????
}
#endregion
}
}
Es ist nur der ein Superheld, der sich selbst für Super hält
Würde mich über Hilfe sehr freuen.
Es ist nur der ein Superheld, der sich selbst für Super hält