Mostrando entradas con la etiqueta word. Mostrar todas las entradas
Mostrando entradas con la etiqueta word. Mostrar todas las entradas

Funciones para trabajar con Word

Aquí tienen una serie de funciones escritas en Delphi que según mi opinión son bastantes útiles cuando queremos programar una aplicación que utilice  documentos Word.



Crear un documento.

Hacer visible un documento.

Añadir un documento.

Insertar texto en...

Graba un documento.



Cierra un documento.

Abre un documento.

Cursor al principio de ...

Encuentra texto.

Pega texto.

Encuentra y Pega texto.

Abre el diálogo de la impresora.

Crea una tabla.

Dimensiona una tabla.

Tamaño de la tabla.

Pon texto en la tabla.

Mezcla celdas.

Selecciona celdas de una tabla.

Ir a la siguiente o anterior tabla.

Obtiene las columnas de una tabla.

Añade una fila a una tabla.

Crea una caja de texto.

Obtiene el índice de la forma gráfica.

Pone el nombre a un shape.

Crea una línea.

Crea una imagen.

Borra un shape.





Crea un documento Word:






uses ComObj;

procedure TForm1.Button1Click(Sender: TObject);
var
MSWord: Variant;
begin
try
MsWord := GetActiveOleObject('Word.Application');
except
try
MsWord := CreateOleObject('Word.Application');
MsWord.Visible := True;
except
Exception.Create('Error');
end;
end;
MSWord.Documents.Add;
MSWord.Selection.Font.Size := 12;
MSWord.Selection.TypeText('Arial');
MSWord.Selection.Font.Bold := true;
MSWord.Selection.TypeText(#13#10'new');
MSWord.ActiveDocument.SaveAs('C:\doc1.doc');
end;



Hacer visible un documento



Function VisibleWord (visible:boolean):boolean;


begin


VisibleWord:=true;


try


W.visible:= visible;


except


VisibleWord:=false;


end;


End;




Añadir un documento



Function AddDoc:boolean;


Var Doc_:variant;


begin


AddDoc:=true;


try


Doc_:=W.Documents;


Doc_.Add;


except


AddDoc:=false;


end;


End;










Function SetTextToDoc(text_: string;InsertAfter_: boolean): boolean;


var Rng_:variant;


begin


SetTextToDoc:=true;


try


Rng_:=W.ActiveDocument.Range;


if InsertAfter_


then Rng_.InsertAfter(text_)


else Rng_.InsertBefore(text_);


except


SetTextToDoc:=false;


end;


End;









En esta función, se usa el objeto Range y sus métodos InsertBefore InsertAfter para insertar texto en el documento en la posición del cursor.






if InsertAfter_


then W.ActiveDocument.Range. InsertAfter(text_)


else W.ActiveDocument.Range. InsertBefore(text_);









Graba un documento:






Function SaveDocAs(file_:string):boolean;


begin


SaveDocAs:=true;


try


W.ActiveDocument.SaveAs(file_);


except


SaveDocAs:=false;


end;


End;





Cierra un documento:




Function CloseDoc:boolean;


begin


CloseDoc:=true;


try


W.ActiveDocument.Close;


except


CloseDoc:=false;


end;


End;





Abre un documento:


var




Doc_:=W.Documents;


Doc_.Open(file_);











Function OpenDoc (file_:string):boolean;


Var
Doc_:variant;


begin


OpenDoc:=true;


try


Doc_:=W.Documents;


Doc_.Open(file_);


except


OpenDoc:=false;


end;


End;





Cursor al principio de ...




Function StartOfDoc:boolean;


begin


StartOfDoc:=true;


try


W.Selection.End:=0;


W.Selection.Start:=0;


except


StartOfDoc:=false;


end;


End;







Encuentra texto:




Function FindTextDoc (text_:string):boolean;


begin


FindTextDoc:=true;


Try


W.Selection.Find.Forward:=true;


W.Selection.Find.Text:=text_;


FindTextDoc := W.Selection.Find.Execute;


except


FindTextDoc:=false;


end;


End;





Pega texto:




Function PasteTextDoc (text_:string):boolean;


begin


PasteTextDoc:=true;


Try


W.Selection.Delete;


W.Selection.InsertAfter (text_);


except


PasteTextDoc:=false;


end;


End;





Encuentra y Pega texto:




Function FindAndPasteTextDoc


(findtext_,pastetext_:string): boolean;


begin


FindAndPasteTextDoc:=true;


try


W.Selection.Find.Forward:=true;


W.Selection.Find.Text:= findtext_;


if
W.Selection.Find.Execute
then
begin


 
W.Selection.Delete;


 
W.Selection.InsertAfter (pastetext_);


end
else
FindAndPasteTextDoc:=false;


except


FindAndPasteTextDoc:=false;


end;


End;





Abre el diálogo de la impresora:




Function PrintDialogWord:boolean;


Const wdDialogFilePrint=88;


begin


PrintDialogWord:=true;


try


W.Dialogs.Item(wdDialogFilePrint).Show;


except


PrintDialogWord:=false;


end;


End;





Crea una tabla:




Function CreateTable(NumRows, NumColumns:integer;


var
index:integer):boolean;


var
sel_:variant;


begin


CreateTable:=true;


try


sel_:=W.selection;


W.ActiveDocument.Tables.Add (Range:=sel_.Range,NumRows:
=NumRows,


 
NumColumns:=NumColumns);


index:=W.ActiveDocument. Tables.Count;


except


CreateTable:=false;


end;


End;





Dimensiona una tabla:




Function SetSizeTable(Table:integer; RowsHeight,


ColumnsWidth:real):boolean;


begin


SetSizeTable:=true;


try


W.ActiveDocument.Tables.Item
(Table).Columns.Width:=ColumnsWidth;


W.ActiveDocument.Tables.Item(Table).
Rows.Height:=RowsHeight;


except


SetSizeTable:=false;


end;


End;





De manera similar, se puede definir la altura de cualquier línea o el ancho de cualquier columna que queramos.







Function SetHeightRowTable(Table,Row:integer;


RowHeight:real):boolean;


begin


SetHeightRowTable:=true;


try


W.ActiveDocument.Tables.Item(Table).Rows.item(Row).Height:=RowHeight;


except


SetHeightRowTable:=false;


end;


End;


Function SetWidthColumnTable(Table,Column: integer;


ColumnWidth:real):boolean;


begin


SetWidthColumnTable:=true;


try


W.ActiveDocument.Tables.Item(Table).Columns.


 
Item(Column).Width:=ColumnWidth;


except


SetWidthColumnTable:=false;


end;


End;





Tamaño de la tabla:




Function GetSizeTable(Table:integer;var RowsHeight,


ColumnsWidth: real):boolean;


begin


GetSizeTable:=true;


try


ColumnsWidth:=W.ActiveDocument.
Tables.Item(Table).Columns.Width;


RowsHeight:=W.ActiveDocument.
Tables.Item(Table).Rows.Height;


except


GetSizeTable:=false;


end;


End;





Pon texto en la tabla:




Function SetTextToTable(Table:integer;Row,
Column:integer;


text:string):boolean;


begin


SetTextToTable:=true;


try


W.ActiveDocument.Tables.Item(Table).Columns.Item(Column).


 
Cells.Item(Row).Range.Text:=text;


except


SetTextToTable:=false;


end;


End;





Mezcla celdas:




Function SetMergeCellsTable(Table:integer;Row1,


Column1,Row2,Column2:integer):boolean;


var
Cel:variant;


begin


SetMergeCellsTable:=true;


try


Cel:=W.ActiveDocument.Tables.I
tem(Table).Cell(Row2,Column2);


W.ActiveDocument.Tables.Item(Table).
Cell(Row1,Column1).Merge(Cel);


except


SetMergeCellsTable:=false;


end;


End;





Selecciona celdas de una tabla:




Function GetSelectionTable:boolean;


const wdWithInTable=12;


begin


GetSelectionTable:=true;


try


GetSelectionTable:=W.Selection.Information(wdWithInTable);


except


GetSelectionTable:=false;


end;


End;





Ir a la siguiente o anterior tabla:




Function GoToNextTable (table_:integer):boolean;


const wdGoToTable=2;


begin


GoToNextTable:=true;


try


W.Selection.GoToNext (wdGoToTable);


except


GoToNextTable:=false;


end;


End;


Function GoToPreviousTable (table_:integer):boolean;


const wdGoToTable=2;


begin


GoToPreviousTable:=true;


try


W.Selection.GoToPrevious(wdGoToTable);


except


GoToPreviousTable:=false;


end;


End;








Obtiene las columnas de una tabla:




Function GetColumnsRowsTable(table_:integer;


var
Columns,Rows:integer):boolean;


const


wdMaximumNumberOfColumns=18;


wdMaximumNumberOfRows=15;


begin


GetColumnsRowsTable:=true;


try


Columns:=W.Selection.Information
(wdMaximumNumberOfColumns);


Rows:=W.Selection.Information
(wdMaximumNumberOfRows);


except


GetColumnsRowsTable:=false;


end;


End;








Añade una fila a una tabla:




Function AddRowTableDoc (table_:integer):boolean;


begin


AddRowTableDoc:=true;


try


W.ActiveDocument.Tables.Item(table_).Rows.Add;


except


AddRowTableDoc:=false;


end;


End;







Function InsertRowsTableDoc(table_,position_,


count_:integer): boolean;


begin


InsertRowsTableDoc:=true;


try


W.ActiveDocument.Tables.Item(table_).Rows.Item(position_).Select;


W.Selection.InsertRows (count_);


except


InsertRowsTableDoc:=false;


end;


End;





Crea una caja de texto:




Function CreateTextBox (Left,Top,Width,Height:real;


var
name:string):boolean;


const msoTextOrientationHorizontal=1;


begin


CreateTextBox:=true;


try


name:=W.ActiveDocument.Shapes.AddTextbox


(msoTextOrientationHorizontal,Left,Top,Width,Height).Name;


except


CreateTextBox:=false;


end;


End;







Function TextToTextBox (TextBox:variant;text:
string):boolean;


const
msoTextBox=
17;


begin


TextToTextBox:=true;


try


if
w.ActiveDocument.Shapes.Item(TextBox).Type = msoTextBox then


 
W.ActiveDocument.Shapes.Item(TextBox).TextFrame.TextRange.Text:=Text


else
TextToTextBox:=false;


except


TextToTextBox:=false;


end;


End;





Obtiene el índice de la forma gráfica:




Function GetNameIndexShape (NameShape:variant): variant;


begin


try


GetNameIndexShape:=W.ActiveDocument.Shapes.Item(NameShape).Name;


except


GetNameIndexShape:=false;


end;


End;





Pone el nombre a un shape:




Function SetNewNameShape (NameShape:variant;


NewNameShape:string):string;


begin


try


W.ActiveDocument.Shapes.Item(NameShape).Name:=NewNameShape;


SetNewNameShape:=NewNameShape;


except


SetNewNameShape:='';


end;


End;





Crea una línea:




Function CreateLine (BeginX,BeginY,EndX,EndY: real;


var
name:string):boolean;


begin


CreateLine:=true;


try


name:=W.ActiveDocument.Shapes.AddLine(BeginX,BeginY,EndX,EndY).Name;


except


CreateLine:=false;


end;


End;





Crea una imagen:




Function CreatePicture(FileName:string;Left,Top: real;


var
name:string):boolean;


begin


CreatePicture:=true;


try


name:=W.ActiveDocument.Shapes.AddPicture(FileName).Name;


W.ActiveDocument.Shapes.Item (name).Left:=Left;


W.ActiveDocument.Shapes.Item(name). Top:=Top;


except


CreatePicture:=false;


end;


End;





Borra un shape:




Function DeleteShape (NameShape:variant): variant;


Begin


DeleteShape:=true;


try


W.ActiveDocument.Shapes.Item (NameShape).Delete;


except


DeleteShape:=false;


end;


End;






 











FAQ Word / Excel

PREGUNTAS



¿Cómo mover el cursor hasta el final de un documento Word?

¿Cómo cambiar el tipo de letra de una celda?

¿Cómo cambiar el color de la tabla?

¿Cómo imprimir sin mostrar el cuadro de diálogo?

Cómo alinear texto en Word

Utilizar Excel a través de la interfaz COM

Utilizar Excel usando OLE

COMPROBAR SI OLE está instalado

¿Cómo exportar una tabla Word a un StringGrid?



RESPUESTAS



¿Cómo mover el cursor hasta el final de un documento Word?


Function EndOfDoc:boolean;


begin


EndOfDoc:=true;


try


W.ActiveDocument.Range.Select;


W.Selection.Start:=W.Selection.End;


except


EndOfDoc:=false;


end;


End;





¿Cómo cambiar el tipo de letra de una celda?




Function SelectCell(Table:integer;


Row,Column:integer):boolean;


begin


SelectCell:=true;


try


W.ActiveDocument.Tables.Item(Table).Columns.Item


 
(Column).Cells.Item(Row).Select;


except


SelectCell:=false;


end;


End;





Function FontToEFont(font:Tfont;EFont:variant;





ColorIndex:integer):boolean;


begin


FontToEFont:=true;


try


EFont.Name:=font.Name;


if
fsBold
in
font.Style


 
then
EFont.Bold:=True 


 
else
EFont.Bold:=False; 


if
fsItalic
in
font.Style


 
then
EFont.Italic:=True


 
else
EFont.Italic:=False; 


EFont.Size:=font.Size; 


if
fsStrikeOut
in
font.Style


 
then
EFont.Strikethrough:=True 


 
else
EFont.Strikethrough:=False; 


if
fsUnderline
in
font.Style


 
then
EFont.Underline:=wdUnderlineSingle 


 
else
EFont.Underline:=wdUnderlineNone; 


EFont.ColorIndex:=ColorIndex; 


except


FontToEFont:=false;


end;


End;





Cuando se selecciona un objeto, podemos cambiar la fuente, para ello utilizamos la siguiente función para la selección de objetos:




Function SetFontSelection(font:Tfont;


ColorIndex:integer):boolean;


begin


SetFontSelection:=true;


try


SetFontSelection:=FontToEFont(font,W.Selection.font,ColorIndex);


except


SetFontSelection:=false;


end;


End;





¿Cómo cambiar el color de la tabla?


W.ActiveDocument.Tables.Item(tab_).Columns.Item(col_).Cells.Item(row_).Borders.Item(wdBorderTop).ColorIndex:=wdDarkRed;





¿Cómo imprimir sin mostrar el cuadro de diálogo?




Function PrintOutDoc(NumCopies:integer):boolean;


begin


PrintOutDoc:=true;


try


W.ActiveDocument.PrintOut(NumCopies);


except


PrintOutDoc:=false;


end;





Cómo alinear texto




W.Selection.ParagraphFormat.Alignment:=wdAlignParagraphCenter;


W.Selection.ParagraphFormat.Alignment:=wdAlignParagraphRight;


W.Selection.ParagraphFormat.Alignment:=wdAlignParagraphJustify;





Utilizar Excel a través de la interfaz COM





EJEMPLO 1 




var
Excel, WorkBook, Sheet: Variant;


begin


Excel :=
CreateOleObject(
'Excel.Application');


Excel.WorkBooks.Open(FileName,False);


WorkBook
:= Excel.WorkBooks.Item[
1];


Sheet :=
Workbook.Sheets.Item[
3];


Sheet.Cells[1,2]:='ASDFG';


Sheet.Cells[2,2]:=230;





EJEMPLO 2


uses


ComObj,
ActiveX;





var


Row,
Col: integer;


DestRange: OleVariant;


Excel:
Variant;





begin


Excel :=
CreateOleObject(
'Excel.Application');


Excel.Visible := True;


Excel.WorkBooks.Add; 


Excel.ActiveSheet.Range['A2', 'B3'].Value := 'Тест';


Excel.ActiveSheet.Range['A4', 'B5'].Value := 42;


Excel.ActiveSheet.Range['A10', 'A11'].Formula := '=RAND()';


Excel.ActiveSheet.Cells.Item[1, 1].Value := 'prueba';





Row:=1;


Col:=3;


Excel.ActiveSheet.Cells.Item[Row, Col].Value := 'prueba';





DestRange := Excel.Range['D6', 'F10'];


Excel.Range['A1', 'C5'].Copy(DestRange);





Excel.Range['A2', 'A2'].Font.Size := 20;


Excel.Range['A2', 'A2'].Font.FontStyle := 'Bold';


Excel.Range['A2', 'A2'].Font.Color := clFuchsia;


Excel.Range['A2', 'A2'].Font.Name := 'Arial';


Excel.Range['B2', 'C6'].Interior.Color := RGB(223,
123, 123);


end;





EJEMPLO 3







uses


ComObj,
ActiveX;





var


Excel:
Variant;


WBk :
OleVariant;


SaveChanges: OleVariant;


begin


Excel :=
CreateOleObject(
'Excel.Application');


Excel.Visible := True;


WBk :=
Excel.WorkBooks.Open(
'C:\Test.xls');




...





WBk.Close(SaveChanges := True);


Excel.Quit;


end;








Utilizar Excel usando OLE







{


Ejemplo para imprimir un archivo utilizando OLE


}


uses


ComObj;





procedure TForm1.Button1Click(Sender: TObject);


var


ExcelApp: OLEVariant;


begin


//
Create an Excel instance


//
Excel Instanz erzeugen


ExcelApp
:= CreateOleObject(
'Excel.Application');


try


  
ExcelApp.Workbooks.Open(
'C:\test\xyz.xls');


  
// you can also modify
some settings from PageSetup


  
// Man kann auch noch
einige Einstellungen von "Seite Einrichten" anpassen


  
ExcelApp.ActiveSheet.PageSetup.Orientation := xlLandscape;


  
// Print it out


  
// Ausdrucken


  
ExcelApp.Worksheets.PrintOut;


finally


  
// Close Excel


  
// Excel wieder
schliessen


  
if
not
VarIsEmpty(ExcelApp)
then


  
begin


    
ExcelApp.Quit;


    
ExcelApp := Unassigned;


  
end;


end;


end;  










//COMPROBAR SI OLE está instalado




if
not
IsOLEObjectInstalled(
'Excel.Application') then


  
ShowMessage(
'no instalado')


else


  
ShowMessage(
'instalado');








function IsOLEObjectInstalled(Name: String): boolean;


var


ClassID:
TCLSID;


Rez :
HRESULT;


begin





Rez :=
CLSIDFromProgID(PWideChar(WideString(
Name)), ClassID);





if
Rez = S_OK
then


  
Result := true


else


  
Result := false;


end;








¿Cómo exportar una tabla Word a un StringGrid?







uses


ComObj;





procedure TForm1.Button1Click(Sender: TObject);


const


AWordDoc
=
'C:\xyz\testTable.doc';


var


MSWord,
Table: OLEVariant;


iRows,
iCols, iGridRows, jGridCols, iNumTables, iTableChosen: Integer;


CellText: string;


InputString: string;


begin


try


  
MSWord := CreateOleObject(
'Word.Application');


except


  
// Error....


   Exit;


end;





try


  
MSWord.Visible := False;


  
MSWord.Documents.Open(AWordDoc);





  
// Get number of tables
in document


  
iNumTables := MSWord.ActiveDocument.Tables.Count;





  
InputString := InputBox(IntToStr(iNumTables) +


    
' Tables in Word
Document'
, 'Please Enter Table
Number'
, '1');


  
// Todo: Validate string
for integer, range...


  
iTableChosen := StrToInt(InputString);





  
// access table


   Table
:= MSWord.ActiveDocument.Tables.Item(iTableChosen);


  
// get dimensions of
table


   iCols
:= Table.Rows.Count;


   iRows
:= Table.Columns.Count;


  
// adjust stringgrid
columns


  
StringGrid1.RowCount := iCols;


  
StringGrid1.ColCount := iRows +
1;





  
// loop through cells


  
for
iGridRows :=
1
to
iRows
do


    
for
jGridCols :=
1
to
iCols
do


    
begin


      
CellText := Table.Cell(jGridCols, iGridRows).Range.FormattedText;


      
if
not
VarisEmpty(CellText)
then


      
begin


        
// Remove Tabs


        
CellText := StringReplace(CellText,


           #$D, '',
[rfReplaceAll]);


        
// Remove linebreaks


        
CellText := StringReplace(CellText, #$7,
'',
[rfReplaceAll]);





        
// fill Stringgrid


        
Stringgrid1.Cells[iGridRows, jGridCols] := CellText;


      
end;


    
end;


  
//..


finally


  
MSWord.Quit;


end;


end;





































Simulación del movimiento de los electrones en un campo electrico

Espectacular simulación realizada con OpenGL del movimiento de los electrones cuando atraviesan un campo eléctrico. Como muestra la image...