C#操作Word!
namespace ImportExportToOffice
{
using System;
using System.ComponentModel;
using System.Data;
using System.Windows.Forms;
public class ImportExportToWord
{
private Word.ApplicationClass oWordApplic;
private Word.Document oDoc;
private const string strFileName = @"F:\";
private const string PostfixForWord = @".doc";
private const string PostfixForHtml = @".Html";
构造函数#region 构造函数
public ImportExportToWord()
{
oWordApplic = new Word.ApplicationClass();
}
#endregion
public Word.Document Document
{
get
{
return this.oDoc;
}
}
public Word.ApplicationClass Application
{
get
{
return this.oWordApplic;
}
}
私有方法#region 私有方法
/**//// <summary>
/// 设置Word文档是否可视
/// </summary>
/// <param name="InEnabled">boolean</param>
private void SetVisible( Boolean InEnabled )
{
oWordApplic.Visible = InEnabled;
}
/**//// <summary>
/// 在垃圾回收时,在任务管理器中还存在当前操作的WORD的进程
/// 查阅资料,必须在另一个方法中在调用GC才可以真正的清楚掉,当前的进程
/// </summary>
private void GCForQuit()
{
object missing = System.Reflection.Missing.Value;
oWordApplic.Application.Quit( ref missing, ref missing, ref missing );
if ( oDoc != null )
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(oDoc);
oDoc = null;
}
if ( oWordApplic != null )
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(oWordApplic);
oWordApplic = null;
}
GC.Collect();
}
/**//// <summary>
/// 返回保存文件的FileName
/// </summary>
/// <param name="strDefaultExt">要保存文件的类型</param>
/// <param name="strFilter">文件名筛选器字符串</param>
/// <returns>保存的路径</returns>
private string SaveFileName( string strDefaultExt, string strFilter )
{
string fileName = "";
System.Windows.Forms.SaveFileDialog saveFileDlg = new System.Windows.Forms.SaveFileDialog();
saveFileDlg.DefaultExt = strDefaultExt;
saveFileDlg.Filter = strFilter;
if ( saveFileDlg.ShowDialog() == System.Windows.Forms.DialogResult.OK )
fileName = saveFileDlg.FileName;
return fileName;
}
/**//// <summary>
/// 将被 SaveFileName 取代
/// </summary>
/// <returns></returns>
private string SaveFileToHtmlForName()
{
string fileName = "";
System.Windows.Forms.SaveFileDialog saveFileDlg = new System.Windows.Forms.SaveFileDialog();
saveFileDlg.DefaultExt = "Html";
saveFileDlg.Filter = "html文件 (*.html)|*.htm";
if ( saveFileDlg.ShowDialog() == System.Windows.Forms.DialogResult.OK )
fileName = saveFileDlg.FileName;
return fileName;
}
/**//// <summary>
/// 保存
/// </summary>
private void Save( )
{
oDoc.Save();
}
#endregion
公有方法#region 公有方法
/**//// <summary>
/// 打开一个空的Word模板
/// </summary>
public bool Open( )
{
bool result = false;
try
{
object missing = System.Reflection.Missing.Value;
oDoc = oWordApplic.Documents.Add( ref missing, ref missing, ref missing, ref missing );
oDoc.Activate();
result = true;
}
catch
{
this.Quit();
//throw ( new Exception() );
}
return result;
}
/**//// <summary>
/// 退出
/// </summary>
public void Quit( )
{
GCForQuit();
GC.Collect();
foreach(System.Diagnostics.Process p in System.Diagnostics.Process.GetProcesses())
{
if(p.ProcessName.ToUpper() == "WINWORD")
{
p.Kill();
}
}
}
/**//// <summary>
/// 打开指定的Word文档
/// </summary>
/// <param name="strFileName">指定的Word文档</param>
public bool Open( string strFileName )
{
return this.Open( strFileName, true );
}
/**//// <summary>
/// 打开指定的Word文档并判断是否显示
/// </summary>
/// <param name="strFileName">指定的Word文档</param>
/// <param name="isEnabled">显示与否</param>
public bool Open( string strFileName, bool isEnabled )
{
bool result = false;
if ( strFileName == null || strFileName == "" ) return result;
try
{
object fileName = strFileName;
object readOnly = false;
object isVisible = true;
object missing = System.Reflection.Missing.Value;
#if OFFICEXP
oDoc = oWordApplic.Documents.Open(ref fileName, ref missing,ref readOnly,
ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref isVisible,ref missing,ref missing,ref missing);
#else
oDoc = oWordApplic.Documents.Open(ref fileName, ref missing,ref readOnly,
ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref isVisible);
#endif
oDoc.Activate();
oWordApplic.Visible = isEnabled;
result = true;
}
catch
{
this.Quit();
//throw ( new Exception() );
}
return result;
}
/**//// <summary>
/// 另存
/// </summary>
public bool SaveAs( )
{
object missing = System.Reflection.Missing.Value;
object fileName = SaveFileName( "doc", "doc文件 (*.doc)|*.doc" );
return this.SaveAs( Convert.ToString( fileName ) );
}
/**//// <summary>
/// 另存
/// </summary>
/// <param name="strFileName"></param>
public bool SaveAs( string strFileName )
{
bool result = false;
if ( strFileName == null || strFileName == "" ) return result;
try
{
object missing = System.Reflection.Missing.Value;
object fileName = strFileName ;
#if OFFICEXP
oDoc.SaveAs( ref fileName, ref missing,ref missing, ref missing,ref missing,ref missing,ref missing,
ref missing,ref missing,ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing );
#else
oDoc.SaveAs( ref fileName, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing );
#endif
result = true;
}
catch
{
//throw( new Exception() );
}
finally
{
this.Quit();
}
return result;
}
/**//// <summary>
/// 把Word文档装化为Html文件
/// </summary>
/// <param name="strFileName">要转换的Word文档</param>
public bool WordToHtml( string strFileNameForWord )
{
string saveFileName = strFileName + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + PostfixForHtml;
return this.WordToHtml( strFileNameForWord, saveFileName );
}
/**//// <summary>
/// 把Word文档装化为Html文件
/// </summary>
/// <param name="strFileName">要转换的Word文档</param>
/// <param name="strSaveFileName">要生成的具体的Html页面</param>
public bool WordToHtml( string strFileNameForWord, string strSaveFileName )
{
bool result = false;
if ( strFileNameForWord == null || strFileNameForWord == "" ) return result;
if ( this.Open( strFileNameForWord, false ) )
{
try
{
Type wordType = oWordApplic.GetType();
// 打开文件
Type docsType = oWordApplic.Documents.GetType();
// 转换格式,另存为
Type docType = oDoc.GetType();
object saveFileName = strSaveFileName;
docType.InvokeMember( "SaveAs", System.Reflection.BindingFlags.InvokeMethod, null, oDoc, new object[]{ saveFileName, Word.WdSaveFormat.wdFormatHTML } );
其它格式:#region 其它格式:
/**////wdFormatHTML
///wdFormatDocument
///wdFormatDOSText
///wdFormatDOSTextLineBreaks
///wdFormatEncodedText
///wdFormatRTF
///wdFormatTemplate
///wdFormatText
///wdFormatTextLineBreaks
///wdFormatUnicodeText
//-----------------------------------------------------------------------------------
// docType.InvokeMember( "SaveAs", System.Reflection.BindingFlags.InvokeMethod,
// null, oDoc, new object[]{saveFileName, Word.WdSaveFormat.wdFormatHTML} );
// 退出 Word
//wordType.InvokeMember( "Quit", System.Reflection.BindingFlags.InvokeMethod,
// null, oWordApplic, null );
#endregion
result = true;
}
catch
{
//throw ( new Exception() );
}
finally
{
this.Quit();
}
}
return result;
}
/**//// <summary>
/// 插入文本操作,所有的打开与保存操作在外部执行
/// </summary>
/// <param name="strText"></param>
public void InsertText( string strText )
{
oWordApplic.Selection.TypeText( strText );
}
public void InsertText( string strText, int iNum )
{
for ( int i = 0; i < iNum; i++ )
this.InsertText( strText );
}
/**//// <summary>
/// 插入文本操作
/// </summary>
/// <param name="strText">要保存的字符串</param>
public bool InsertTextBySelection( string strText )
{
string strsavefilename = strFileName + DateTime.Now.ToString("yyyyMMddHHmmss") + PostfixForWord;
return this.InsertTextBySelection( strText, strsavefilename );
}
/**//// <summary>
///
/// </summary>
/// <param name="strText">要保存的字符串</param>
/// <param name="strSaveFileName">保存后的doc文件名</param>
public bool InsertTextBySelection( string strText, string strSaveFileName )
{
return this.InsertTextBySelection( strText, strSaveFileName, 20, 20, 0, 0, "华文仿宋" );
}
/**//// <summary>
///
/// </summary>
/// <param name="strText">要保存的字符串</param>
/// <param name="strSaveFileName">保存后的doc文件名</param>
/// <param name="leftindent">首行缩近多少</=param>
/// <param name="size">字体大小</param>
/// <param name="boldbi">是否粗体;1 yes, 0 no</param>
/// <param name="paragraphalignment">对齐方式</param>
public bool InsertTextBySelection( string strText, string strSaveFileName, float firstlineindent , int size, int boldbi,int paragraphalignment, string fontname )
{
bool result = false;
if ( strText == "" || strText == null ) return result;
if ( this.Open() )
{
try
{
string[] strvalue = strText.Split( '$');
if ( strvalue.Length != 0 )
{
oWordApplic.Selection.TypeText( "今天是:"+ DateTime.Now.ToString("yyyy-MM-dd") );
Word.Paragraph para = this.GoToFirstParagraph();
para.Range.Select();
this.SetFontName( fontname );
this.SetFirstLineIndent( firstlineindent );
this.SetFontSize( 20 );
this.setBoldBi( boldbi );
switch ( paragraphalignment )
{
case 0 :
this.SetAlignment(Word.WdParagraphAlignment.wdAlignParagraphLeft);
break;
case 1 :
this.SetAlignment(Word.WdParagraphAlignment.wdAlignParagraphCenter);
break;
case 2:
this.SetAlignment(Word.WdParagraphAlignment.wdAlignParagraphRight);
break;
}
int j = 0;
for( int i= 0; i < strvalue.Length; i++ )
{
this.InsertParagraphAfterByParagraph(para,1); //加1个空行
para = this.GoToEndParagraph(); //定位到第1空行
this.InsertTextBeforeByParagraph( para, strvalue[i] );
para = this.GoToEndParagraph();
para.Range.Select();
this.setBoldBi( boldbi ); //设置标题非粗体字
this.SetFontSize( size ); //设置字体大小
this.SetFontName( fontname ); //设置字体
j++;
if ( j == 9 )
{
this.InsertText( "━━━━", 6 );
j = 0;
}
}
if ( this.SaveAs( strSaveFileName ) )
result = true;
}
}
catch
{
this.Quit();
//throw( new Exception() );
}
}
return result;
}
/**//// <summary>
/// 插入空行
/// </summary>
public void InsertLineBreakBySelection( )
{
oWordApplic.Selection.TypeParagraph();
}
/**//// <summary>
/// 插入指定的空行
/// </summary>
/// <param name="nline">行数</param>
public void InsertLineBreakBySelection( int nline )
{
for ( int i = 0; i < nline; i++ )
this.InsertLineBreakBySelection();
}
/**//// <summary>
/// 换页
/// </summary>
public void InsertPagebreak()
{
object pBreak= (int)Word.WdBreakType.wdPageBreak;
oWordApplic.Selection.InsertBreak( ref pBreak );
}
public void InsertTextBeforeByParagraph( Word.Paragraph paragraph, string strText )
{
paragraph.Range.InsertBefore( strText );
}
public void InsertTextAfterByParagraph( Word.Paragraph paragraph, string strText )
{
paragraph.Range.InsertAfter( strText );
}
public void InsertParagraphBeforeByParagraph( Word.Paragraph paragraph )
{
paragraph.Range.InsertParagraphBefore();
}
public void InsertParagraphBeforeByParagraph( Word.Paragraph paragraph,int nLine )
{
for ( int i = 0; i < nLine; i++ )
paragraph.Range.InsertParagraphBefore();
}
public void InsertParagraphAfterByParagraph( Word.Paragraph paragraph )
{
paragraph.Range.InsertParagraphAfter();
}
public void InsertParagraphAfterByParagraph( Word.Paragraph paragraph, int nLine )
{
for ( int i = 0; i < nLine; i++ )
paragraph.Range.InsertParagraphAfter();
}
/**//// <summary>
/// 数据集转换 即把DataSet转换为Word对象
/// </summary>
/// <param name="ds"></param>
public bool DataSetToWord( DataSet ds, string strFileName )
{
bool result = false;
if ( ds == null ) return result;
if ( strFileName == null || strFileName == "" ) return result;
if ( this.Open() )
{
try
{
Word.Range para = oWordApplic.Application.Selection.Paragraphs.Item(1).Range;
object tableBehavior =System.Reflection.Missing.Value;
object autoFitBehavior =System.Reflection.Missing.Value;
oDoc.Tables.Add( para,
ds.Tables[0].Rows.Count+1, //多的一行用来表示表列
ds.Tables[0].Columns.Count,
ref tableBehavior,
ref autoFitBehavior );
//填充Word表格的列标
for( int intCol = 0; intCol < ds.Tables[0].Columns.Count; intCol++ )
{
oDoc.Tables.Item(1).Cell( 1, intCol+1 ).Range.InsertBefore( ds.Tables[0].Columns[intCol].ColumnName.Trim() );
}
//填充Word表格的内容
for( int intRow = 0; intRow < ds.Tables[0].Rows.Count; intRow++ )
{
for( int intCol = 0; intCol < ds.Tables[0].Columns.Count; intCol++ )
{
oDoc.Tables.Item(1).Cell( intRow+2, intCol+1 ).Range.InsertBefore( ds.Tables[0].Rows[intRow][intCol].ToString().Trim() );
}
}
//保存
if ( this.SaveAs( strFileName ) )
result = true;
}
catch
{
this.Quit();
//throw ( new Exception() );
}
}
return result;
}
/**//// <summary>
/// 采用默认地址保存
/// </summary>
/// <param name="ds"></param>
public bool DataSetToWord( DataSet ds )
{
return this.DataSetToWord( ds, strFileName + ds.Tables[0].TableName.ToString() + PostfixForWord );
}
/**//// <summary>
/// 段落的对齐方式
/// 例如:word.SetAlignment(Word.WdParagraphAlignment.wdAlignParagraphCenter)
/// </summary>
/// <param name="alignment"></param>
public void SetAlignment( Word.WdParagraphAlignment alignment )
{
oWordApplic.Selection.ParagraphFormat.Alignment = alignment;
}
/**//// <summary>
/// 首行缩进
/// </summary>
/// <param name="fltCount">float类型的数值</param>
public void SetFirstLineIndent( float fltCount )
{
oWordApplic.Selection.ParagraphFormat.FirstLineIndent = fltCount;
}
/**//// <summary>
/// 左缩进
/// </summary>
/// <param name="fltCount">float类型的数值</param>
public void SetLeftIndent( float fltCount )
{
oWordApplic.Selection.ParagraphFormat.LeftIndent = fltCount;
}
/**//// <summary>
/// 右缩进
/// </summary>
/// <param name="fltCount">float类型的数值</param>
public void SetRightIndent(float fltCount)
{
oWordApplic.Selection.ParagraphFormat.RightIndent = fltCount;
}
/**//// <summary>
/// 设置字体类型
/// </summary>
/// <param name="strType"></param>
public void SetFont( string strType )
{
switch (strType)
{
case "Bold":
oWordApplic.Selection.Font.Bold = 1;
break;
case "Italic":
oWordApplic.Selection.Font.Italic = 1;
break;
case "Underlined":
oWordApplic.Selection.Font.Subscript = 0;
break;
}
}
/**//// <summary>
/// 设置默认字体
/// </summary>
public void SetFont( )
{
oWordApplic.Selection.Font.Bold = 0;
oWordApplic.Selection.Font.Italic = 0;
oWordApplic.Selection.Font.Subscript = 0;
}
/**//// <summary>
/// 设置字体名称
/// </summary>
/// <param name="strType"></param>
public void SetFontName( string strType )
{
oWordApplic.Selection.Font.Name = strType;
}
/**//// <summary>
/// 设置字体颜色
/// </summary>
/// <param name="Color"></param>
public void SetFontColor( Word.WdColor Color)
{
oWordApplic.Selection.Font.Color = Color;
}
/**//// <summary>
/// 设置字体大小
/// </summary>
/// <param name="nSize"></param>
public void SetFontSize( int nSize )
{
oWordApplic.Selection.Font.Size = nSize;
}
/**//// <summary>
/// 设置是否有粗体,0->否 ,1->是
/// </summary>
/// <param name="intBoldBi"></param>
public void setBoldBi( int intBoldBi )
{
oWordApplic.Selection.Font.BoldBi = intBoldBi;
//oWordApplic.Selection.Font.Bold = intBoldBi;
}
public void SetBoldSize( int intBold )
{
oWordApplic.Selection.Font.Bold = intBold;
}
public void SetUnderLine( Word.WdUnderline underLine )
{
oWordApplic.Selection.Font.Underline = underLine;
}
public void SetUnderLineColor( Word.WdColor Color )
{
oWordApplic.Selection.Font.UnderlineColor = Color;
}
/**//// <summary>
/// 定位到书签
/// </summary>
/// <param name="strBookMarkName"></param>
public void GotoBookMark( string strBookMarkName )
{
object missing = System.Reflection.Missing.Value;
object Bookmark = (int)Word.WdGoToItem.wdGoToBookmark;
object NameBookMark = strBookMarkName;
oWordApplic.Selection.GoTo( ref Bookmark, ref missing, ref missing,ref NameBookMark );
}
/**//// <summary>
/// 定位到文档开头
/// </summary>
public void GoToTheBeginning( )
{
object missing = System.Reflection.Missing.Value;
object unit;
unit = Word.WdUnits.wdStory ;
oWordApplic.Selection.HomeKey ( ref unit, ref missing );
}
/**//// <summary>
/// 定位到文档结尾
/// </summary>
public void GoToTheEnd( )
{
object missing = System.Reflection.Missing.Value;
object unit;
unit = Word.WdUnits.wdStory ;
oWordApplic.Selection.EndKey ( ref unit, ref missing );
}
/**//// <summary>
/// 定位到首段
/// </summary>
/// <returns></returns>
public Word.Paragraph GoToFirstParagraph()
{
return this.oWordApplic.Selection.Paragraphs.First;
}
/**//// <summary>
/// 定位到尾段
/// </summary>
/// <returns></returns>
public Word.Paragraph GoToEndParagraph()
{
return this.oWordApplic.Selection.Paragraphs.Last ;
}
/**//// <summary>
/// 向后定位到指定段落
/// </summary>
/// <param name="para"></param>
/// <param name="count"></param>
public void GoToNextParagraph(ref Word.Paragraph para,ref object count)
{
para.Next(ref count) ;
}
/**//// <summary>
/// 向前定位到指定段落
/// </summary>
/// <param name="para"></param>
/// <param name="count"></param>
public void GoToPreviousParagraph( ref Word.Paragraph para, ref object count )
{
para.Previous( ref count ) ;
}
public void GoToTheTable( int ntable )
{
object missing = System.Reflection.Missing.Value;
object what;
what = Word.WdUnits.wdTable ;
object which;
which = Word.WdGoToDirection.wdGoToFirst;
object count;
count = 1 ;
oWordApplic.Selection.GoTo( ref what, ref which, ref count, ref missing );
}
public void GoToRightCell( )
{
object missing = System.Reflection.Missing.Value;
object direction;
direction = Word.WdUnits.wdCell;
oWordApplic.Selection.MoveRight( ref direction, ref missing, ref missing );
}
public void GoToLeftCell( )
{
object missing = System.Reflection.Missing.Value;
object direction;
direction = Word.WdUnits.wdCell;
oWordApplic.Selection.MoveLeft( ref direction, ref missing, ref missing );
}
public void GoToDownCell( )
{
object missing = System.Reflection.Missing.Value;
object direction;
direction = Word.WdUnits.wdLine;
oWordApplic.Selection.MoveDown( ref direction, ref missing, ref missing );
}
public void GoToUpCell( )
{
object missing = System.Reflection.Missing.Value;
object direction;
direction = Word.WdUnits.wdLine;
oWordApplic.Selection.MoveUp( ref direction, ref missing, ref missing );
}
public Boolean ExecuteReplace( Word.Find find )
{
return ExecuteReplace( find, Word.WdReplace.wdReplaceAll );
}
public Boolean ExecuteReplace( Word.Find find, Object replaceOption )
{
// Simple wrapper around Find.Execute:
Object findText = Type.Missing;
Object matchCase = Type.Missing;
Object matchWholeWord = Type.Missing;
Object matchWildcards = Type.Missing;
Object matchSoundsLike = Type.Missing;
Object matchAllWordForms = Type.Missing;
Object forward = Type.Missing;
Object wrap = Type.Missing;
Object format = Type.Missing;
Object replaceWith = Type.Missing;
Object replace = replaceOption;
Object matchKashida = Type.Missing;
Object matchDiacritics = Type.Missing;
Object matchAlefHamza = Type.Missing;
Object matchControl = Type.Missing;
return find.Execute( ref findText, ref matchCase, ref matchWholeWord,
ref matchWildcards, ref matchSoundsLike, ref matchAllWordForms,
ref forward, ref wrap, ref format, ref replaceWith, ref replace,
ref matchKashida, ref matchDiacritics, ref matchAlefHamza,
ref matchControl );
}
public Boolean ExecuteFind( Word.Find find )
{
return ExecuteFind( find, find.Text, Type.Missing, Type.Missing );
}
public Boolean ExecuteFind( Word.Find find, string strFindText )
{
return ExecuteFind( find, strFindText, Type.Missing, Type.Missing );
}
public Boolean ExecuteFind(
Word.Find find, string strFindText, Object wrapFind, Object forwardFind )
{
// Simple wrapper around Find.Execute:
Object findText ;
Object matchCase = Type.Missing;
Object matchWholeWord = Type.Missing;
Object matchWildcards = Type.Missing;
Object matchSoundsLike = Type.Missing;
Object matchAllWordForms = Type.Missing;
Object forward = forwardFind;
Object wrap = wrapFind;
Object format = Type.Missing;
Object replaceWith = Type.Missing;
Object replace = Type.Missing;
Object matchKashida = Type.Missing;
Object matchDiacritics = Type.Missing;
Object matchAlefHamza = Type.Missing;
Object matchControl = Type.Missing;
if ( ( strFindText == "" )||( strFindText == string.Empty ) )
findText = find.Text;
else
findText = strFindText;
find.ClearFormatting();
return find.Execute( ref findText, ref matchCase, ref matchWholeWord,
ref matchWildcards, ref matchSoundsLike, ref matchAllWordForms,
ref forward, ref wrap, ref format, ref replaceWith, ref replace,
ref matchKashida, ref matchDiacritics, ref matchAlefHamza,
ref matchControl );
}
public Boolean FindInSelection( Word.Selection Selection, string strFindText )
{
return this.ExecuteFind( Selection.Find,strFindText,System.Type.Missing,System.Type.Missing );
}
public Boolean FindInSelection( Word.Selection Selection, string strFindText, Object wrapFind, Object forwardFind )
{
return this.ExecuteFind( Selection.Find, strFindText, wrapFind, forwardFind );
}
public Boolean FindInRange( Word.Range range,string strFindText )
{
Boolean blnReturn =this.ExecuteFind( range.Find, strFindText, Type.Missing, Type.Missing );
range.Select();
return blnReturn;
}
public void FindInAllDocument( string strFindText )
{
int intFound = 0;
Object start = 0;
Object end = this.oDoc.Characters.Count;
Word.Range rngDoc = oDoc.Range( ref start, ref end );
Word.Find fnd = rngDoc.Find;
fnd.ClearFormatting();
fnd.Forward = true;
fnd.Text = strFindText;
ExecuteFind( fnd );
while ( fnd.Found )
{
rngDoc.Font.Color = Word.WdColor.wdColorRed;
rngDoc.Font.Bold = 600;
intFound++;
ExecuteFind( fnd );
}
MessageBox.Show( String.Format( "lorem found {0} times.", intFound ), "FindInLoopAndFormat" );
}
#endregion
}
}
{
using System;
using System.ComponentModel;
using System.Data;
using System.Windows.Forms;
public class ImportExportToWord
{
private Word.ApplicationClass oWordApplic;
private Word.Document oDoc;
private const string strFileName = @"F:\";
private const string PostfixForWord = @".doc";
private const string PostfixForHtml = @".Html";
构造函数#region 构造函数
public ImportExportToWord()
{
oWordApplic = new Word.ApplicationClass();
}
#endregion
public Word.Document Document
{
get
{
return this.oDoc;
}
}
public Word.ApplicationClass Application
{
get
{
return this.oWordApplic;
}
}
私有方法#region 私有方法
/**//// <summary>
/// 设置Word文档是否可视
/// </summary>
/// <param name="InEnabled">boolean</param>
private void SetVisible( Boolean InEnabled )
{
oWordApplic.Visible = InEnabled;
}
/**//// <summary>
/// 在垃圾回收时,在任务管理器中还存在当前操作的WORD的进程
/// 查阅资料,必须在另一个方法中在调用GC才可以真正的清楚掉,当前的进程
/// </summary>
private void GCForQuit()
{
object missing = System.Reflection.Missing.Value;
oWordApplic.Application.Quit( ref missing, ref missing, ref missing );
if ( oDoc != null )
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(oDoc);
oDoc = null;
}
if ( oWordApplic != null )
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(oWordApplic);
oWordApplic = null;
}
GC.Collect();
}
/**//// <summary>
/// 返回保存文件的FileName
/// </summary>
/// <param name="strDefaultExt">要保存文件的类型</param>
/// <param name="strFilter">文件名筛选器字符串</param>
/// <returns>保存的路径</returns>
private string SaveFileName( string strDefaultExt, string strFilter )
{
string fileName = "";
System.Windows.Forms.SaveFileDialog saveFileDlg = new System.Windows.Forms.SaveFileDialog();
saveFileDlg.DefaultExt = strDefaultExt;
saveFileDlg.Filter = strFilter;
if ( saveFileDlg.ShowDialog() == System.Windows.Forms.DialogResult.OK )
fileName = saveFileDlg.FileName;
return fileName;
}
/**//// <summary>
/// 将被 SaveFileName 取代
/// </summary>
/// <returns></returns>
private string SaveFileToHtmlForName()
{
string fileName = "";
System.Windows.Forms.SaveFileDialog saveFileDlg = new System.Windows.Forms.SaveFileDialog();
saveFileDlg.DefaultExt = "Html";
saveFileDlg.Filter = "html文件 (*.html)|*.htm";
if ( saveFileDlg.ShowDialog() == System.Windows.Forms.DialogResult.OK )
fileName = saveFileDlg.FileName;
return fileName;
}
/**//// <summary>
/// 保存
/// </summary>
private void Save( )
{
oDoc.Save();
}
#endregion
公有方法#region 公有方法
/**//// <summary>
/// 打开一个空的Word模板
/// </summary>
public bool Open( )
{
bool result = false;
try
{
object missing = System.Reflection.Missing.Value;
oDoc = oWordApplic.Documents.Add( ref missing, ref missing, ref missing, ref missing );
oDoc.Activate();
result = true;
}
catch
{
this.Quit();
//throw ( new Exception() );
}
return result;
}
/**//// <summary>
/// 退出
/// </summary>
public void Quit( )
{
GCForQuit();
GC.Collect();
foreach(System.Diagnostics.Process p in System.Diagnostics.Process.GetProcesses())
{
if(p.ProcessName.ToUpper() == "WINWORD")
{
p.Kill();
}
}
}
/**//// <summary>
/// 打开指定的Word文档
/// </summary>
/// <param name="strFileName">指定的Word文档</param>
public bool Open( string strFileName )
{
return this.Open( strFileName, true );
}
/**//// <summary>
/// 打开指定的Word文档并判断是否显示
/// </summary>
/// <param name="strFileName">指定的Word文档</param>
/// <param name="isEnabled">显示与否</param>
public bool Open( string strFileName, bool isEnabled )
{
bool result = false;
if ( strFileName == null || strFileName == "" ) return result;
try
{
object fileName = strFileName;
object readOnly = false;
object isVisible = true;
object missing = System.Reflection.Missing.Value;
#if OFFICEXP
oDoc = oWordApplic.Documents.Open(ref fileName, ref missing,ref readOnly,
ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref isVisible,ref missing,ref missing,ref missing);
#else
oDoc = oWordApplic.Documents.Open(ref fileName, ref missing,ref readOnly,
ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref isVisible);
#endif
oDoc.Activate();
oWordApplic.Visible = isEnabled;
result = true;
}
catch
{
this.Quit();
//throw ( new Exception() );
}
return result;
}
/**//// <summary>
/// 另存
/// </summary>
public bool SaveAs( )
{
object missing = System.Reflection.Missing.Value;
object fileName = SaveFileName( "doc", "doc文件 (*.doc)|*.doc" );
return this.SaveAs( Convert.ToString( fileName ) );
}
/**//// <summary>
/// 另存
/// </summary>
/// <param name="strFileName"></param>
public bool SaveAs( string strFileName )
{
bool result = false;
if ( strFileName == null || strFileName == "" ) return result;
try
{
object missing = System.Reflection.Missing.Value;
object fileName = strFileName ;
#if OFFICEXP
oDoc.SaveAs( ref fileName, ref missing,ref missing, ref missing,ref missing,ref missing,ref missing,
ref missing,ref missing,ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing );
#else
oDoc.SaveAs( ref fileName, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing );
#endif
result = true;
}
catch
{
//throw( new Exception() );
}
finally
{
this.Quit();
}
return result;
}
/**//// <summary>
/// 把Word文档装化为Html文件
/// </summary>
/// <param name="strFileName">要转换的Word文档</param>
public bool WordToHtml( string strFileNameForWord )
{
string saveFileName = strFileName + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + PostfixForHtml;
return this.WordToHtml( strFileNameForWord, saveFileName );
}
/**//// <summary>
/// 把Word文档装化为Html文件
/// </summary>
/// <param name="strFileName">要转换的Word文档</param>
/// <param name="strSaveFileName">要生成的具体的Html页面</param>
public bool WordToHtml( string strFileNameForWord, string strSaveFileName )
{
bool result = false;
if ( strFileNameForWord == null || strFileNameForWord == "" ) return result;
if ( this.Open( strFileNameForWord, false ) )
{
try
{
Type wordType = oWordApplic.GetType();
// 打开文件
Type docsType = oWordApplic.Documents.GetType();
// 转换格式,另存为
Type docType = oDoc.GetType();
object saveFileName = strSaveFileName;
docType.InvokeMember( "SaveAs", System.Reflection.BindingFlags.InvokeMethod, null, oDoc, new object[]{ saveFileName, Word.WdSaveFormat.wdFormatHTML } );
其它格式:#region 其它格式:
/**////wdFormatHTML
///wdFormatDocument
///wdFormatDOSText
///wdFormatDOSTextLineBreaks
///wdFormatEncodedText
///wdFormatRTF
///wdFormatTemplate
///wdFormatText
///wdFormatTextLineBreaks
///wdFormatUnicodeText
//-----------------------------------------------------------------------------------
// docType.InvokeMember( "SaveAs", System.Reflection.BindingFlags.InvokeMethod,
// null, oDoc, new object[]{saveFileName, Word.WdSaveFormat.wdFormatHTML} );
// 退出 Word
//wordType.InvokeMember( "Quit", System.Reflection.BindingFlags.InvokeMethod,
// null, oWordApplic, null );
#endregion
result = true;
}
catch
{
//throw ( new Exception() );
}
finally
{
this.Quit();
}
}
return result;
}
/**//// <summary>
/// 插入文本操作,所有的打开与保存操作在外部执行
/// </summary>
/// <param name="strText"></param>
public void InsertText( string strText )
{
oWordApplic.Selection.TypeText( strText );
}
public void InsertText( string strText, int iNum )
{
for ( int i = 0; i < iNum; i++ )
this.InsertText( strText );
}
/**//// <summary>
/// 插入文本操作
/// </summary>
/// <param name="strText">要保存的字符串</param>
public bool InsertTextBySelection( string strText )
{
string strsavefilename = strFileName + DateTime.Now.ToString("yyyyMMddHHmmss") + PostfixForWord;
return this.InsertTextBySelection( strText, strsavefilename );
}
/**//// <summary>
///
/// </summary>
/// <param name="strText">要保存的字符串</param>
/// <param name="strSaveFileName">保存后的doc文件名</param>
public bool InsertTextBySelection( string strText, string strSaveFileName )
{
return this.InsertTextBySelection( strText, strSaveFileName, 20, 20, 0, 0, "华文仿宋" );
}
/**//// <summary>
///
/// </summary>
/// <param name="strText">要保存的字符串</param>
/// <param name="strSaveFileName">保存后的doc文件名</param>
/// <param name="leftindent">首行缩近多少</=param>
/// <param name="size">字体大小</param>
/// <param name="boldbi">是否粗体;1 yes, 0 no</param>
/// <param name="paragraphalignment">对齐方式</param>
public bool InsertTextBySelection( string strText, string strSaveFileName, float firstlineindent , int size, int boldbi,int paragraphalignment, string fontname )
{
bool result = false;
if ( strText == "" || strText == null ) return result;
if ( this.Open() )
{
try
{
string[] strvalue = strText.Split( '$');
if ( strvalue.Length != 0 )
{
oWordApplic.Selection.TypeText( "今天是:"+ DateTime.Now.ToString("yyyy-MM-dd") );
Word.Paragraph para = this.GoToFirstParagraph();
para.Range.Select();
this.SetFontName( fontname );
this.SetFirstLineIndent( firstlineindent );
this.SetFontSize( 20 );
this.setBoldBi( boldbi );
switch ( paragraphalignment )
{
case 0 :
this.SetAlignment(Word.WdParagraphAlignment.wdAlignParagraphLeft);
break;
case 1 :
this.SetAlignment(Word.WdParagraphAlignment.wdAlignParagraphCenter);
break;
case 2:
this.SetAlignment(Word.WdParagraphAlignment.wdAlignParagraphRight);
break;
}
int j = 0;
for( int i= 0; i < strvalue.Length; i++ )
{
this.InsertParagraphAfterByParagraph(para,1); //加1个空行
para = this.GoToEndParagraph(); //定位到第1空行
this.InsertTextBeforeByParagraph( para, strvalue[i] );
para = this.GoToEndParagraph();
para.Range.Select();
this.setBoldBi( boldbi ); //设置标题非粗体字
this.SetFontSize( size ); //设置字体大小
this.SetFontName( fontname ); //设置字体
j++;
if ( j == 9 )
{
this.InsertText( "━━━━", 6 );
j = 0;
}
}
if ( this.SaveAs( strSaveFileName ) )
result = true;
}
}
catch
{
this.Quit();
//throw( new Exception() );
}
}
return result;
}
/**//// <summary>
/// 插入空行
/// </summary>
public void InsertLineBreakBySelection( )
{
oWordApplic.Selection.TypeParagraph();
}
/**//// <summary>
/// 插入指定的空行
/// </summary>
/// <param name="nline">行数</param>
public void InsertLineBreakBySelection( int nline )
{
for ( int i = 0; i < nline; i++ )
this.InsertLineBreakBySelection();
}
/**//// <summary>
/// 换页
/// </summary>
public void InsertPagebreak()
{
object pBreak= (int)Word.WdBreakType.wdPageBreak;
oWordApplic.Selection.InsertBreak( ref pBreak );
}
public void InsertTextBeforeByParagraph( Word.Paragraph paragraph, string strText )
{
paragraph.Range.InsertBefore( strText );
}
public void InsertTextAfterByParagraph( Word.Paragraph paragraph, string strText )
{
paragraph.Range.InsertAfter( strText );
}
public void InsertParagraphBeforeByParagraph( Word.Paragraph paragraph )
{
paragraph.Range.InsertParagraphBefore();
}
public void InsertParagraphBeforeByParagraph( Word.Paragraph paragraph,int nLine )
{
for ( int i = 0; i < nLine; i++ )
paragraph.Range.InsertParagraphBefore();
}
public void InsertParagraphAfterByParagraph( Word.Paragraph paragraph )
{
paragraph.Range.InsertParagraphAfter();
}
public void InsertParagraphAfterByParagraph( Word.Paragraph paragraph, int nLine )
{
for ( int i = 0; i < nLine; i++ )
paragraph.Range.InsertParagraphAfter();
}
/**//// <summary>
/// 数据集转换 即把DataSet转换为Word对象
/// </summary>
/// <param name="ds"></param>
public bool DataSetToWord( DataSet ds, string strFileName )
{
bool result = false;
if ( ds == null ) return result;
if ( strFileName == null || strFileName == "" ) return result;
if ( this.Open() )
{
try
{
Word.Range para = oWordApplic.Application.Selection.Paragraphs.Item(1).Range;
object tableBehavior =System.Reflection.Missing.Value;
object autoFitBehavior =System.Reflection.Missing.Value;
oDoc.Tables.Add( para,
ds.Tables[0].Rows.Count+1, //多的一行用来表示表列
ds.Tables[0].Columns.Count,
ref tableBehavior,
ref autoFitBehavior );
//填充Word表格的列标
for( int intCol = 0; intCol < ds.Tables[0].Columns.Count; intCol++ )
{
oDoc.Tables.Item(1).Cell( 1, intCol+1 ).Range.InsertBefore( ds.Tables[0].Columns[intCol].ColumnName.Trim() );
}
//填充Word表格的内容
for( int intRow = 0; intRow < ds.Tables[0].Rows.Count; intRow++ )
{
for( int intCol = 0; intCol < ds.Tables[0].Columns.Count; intCol++ )
{
oDoc.Tables.Item(1).Cell( intRow+2, intCol+1 ).Range.InsertBefore( ds.Tables[0].Rows[intRow][intCol].ToString().Trim() );
}
}
//保存
if ( this.SaveAs( strFileName ) )
result = true;
}
catch
{
this.Quit();
//throw ( new Exception() );
}
}
return result;
}
/**//// <summary>
/// 采用默认地址保存
/// </summary>
/// <param name="ds"></param>
public bool DataSetToWord( DataSet ds )
{
return this.DataSetToWord( ds, strFileName + ds.Tables[0].TableName.ToString() + PostfixForWord );
}
/**//// <summary>
/// 段落的对齐方式
/// 例如:word.SetAlignment(Word.WdParagraphAlignment.wdAlignParagraphCenter)
/// </summary>
/// <param name="alignment"></param>
public void SetAlignment( Word.WdParagraphAlignment alignment )
{
oWordApplic.Selection.ParagraphFormat.Alignment = alignment;
}
/**//// <summary>
/// 首行缩进
/// </summary>
/// <param name="fltCount">float类型的数值</param>
public void SetFirstLineIndent( float fltCount )
{
oWordApplic.Selection.ParagraphFormat.FirstLineIndent = fltCount;
}
/**//// <summary>
/// 左缩进
/// </summary>
/// <param name="fltCount">float类型的数值</param>
public void SetLeftIndent( float fltCount )
{
oWordApplic.Selection.ParagraphFormat.LeftIndent = fltCount;
}
/**//// <summary>
/// 右缩进
/// </summary>
/// <param name="fltCount">float类型的数值</param>
public void SetRightIndent(float fltCount)
{
oWordApplic.Selection.ParagraphFormat.RightIndent = fltCount;
}
/**//// <summary>
/// 设置字体类型
/// </summary>
/// <param name="strType"></param>
public void SetFont( string strType )
{
switch (strType)
{
case "Bold":
oWordApplic.Selection.Font.Bold = 1;
break;
case "Italic":
oWordApplic.Selection.Font.Italic = 1;
break;
case "Underlined":
oWordApplic.Selection.Font.Subscript = 0;
break;
}
}
/**//// <summary>
/// 设置默认字体
/// </summary>
public void SetFont( )
{
oWordApplic.Selection.Font.Bold = 0;
oWordApplic.Selection.Font.Italic = 0;
oWordApplic.Selection.Font.Subscript = 0;
}
/**//// <summary>
/// 设置字体名称
/// </summary>
/// <param name="strType"></param>
public void SetFontName( string strType )
{
oWordApplic.Selection.Font.Name = strType;
}
/**//// <summary>
/// 设置字体颜色
/// </summary>
/// <param name="Color"></param>
public void SetFontColor( Word.WdColor Color)
{
oWordApplic.Selection.Font.Color = Color;
}
/**//// <summary>
/// 设置字体大小
/// </summary>
/// <param name="nSize"></param>
public void SetFontSize( int nSize )
{
oWordApplic.Selection.Font.Size = nSize;
}
/**//// <summary>
/// 设置是否有粗体,0->否 ,1->是
/// </summary>
/// <param name="intBoldBi"></param>
public void setBoldBi( int intBoldBi )
{
oWordApplic.Selection.Font.BoldBi = intBoldBi;
//oWordApplic.Selection.Font.Bold = intBoldBi;
}
public void SetBoldSize( int intBold )
{
oWordApplic.Selection.Font.Bold = intBold;
}
public void SetUnderLine( Word.WdUnderline underLine )
{
oWordApplic.Selection.Font.Underline = underLine;
}
public void SetUnderLineColor( Word.WdColor Color )
{
oWordApplic.Selection.Font.UnderlineColor = Color;
}
/**//// <summary>
/// 定位到书签
/// </summary>
/// <param name="strBookMarkName"></param>
public void GotoBookMark( string strBookMarkName )
{
object missing = System.Reflection.Missing.Value;
object Bookmark = (int)Word.WdGoToItem.wdGoToBookmark;
object NameBookMark = strBookMarkName;
oWordApplic.Selection.GoTo( ref Bookmark, ref missing, ref missing,ref NameBookMark );
}
/**//// <summary>
/// 定位到文档开头
/// </summary>
public void GoToTheBeginning( )
{
object missing = System.Reflection.Missing.Value;
object unit;
unit = Word.WdUnits.wdStory ;
oWordApplic.Selection.HomeKey ( ref unit, ref missing );
}
/**//// <summary>
/// 定位到文档结尾
/// </summary>
public void GoToTheEnd( )
{
object missing = System.Reflection.Missing.Value;
object unit;
unit = Word.WdUnits.wdStory ;
oWordApplic.Selection.EndKey ( ref unit, ref missing );
}
/**//// <summary>
/// 定位到首段
/// </summary>
/// <returns></returns>
public Word.Paragraph GoToFirstParagraph()
{
return this.oWordApplic.Selection.Paragraphs.First;
}
/**//// <summary>
/// 定位到尾段
/// </summary>
/// <returns></returns>
public Word.Paragraph GoToEndParagraph()
{
return this.oWordApplic.Selection.Paragraphs.Last ;
}
/**//// <summary>
/// 向后定位到指定段落
/// </summary>
/// <param name="para"></param>
/// <param name="count"></param>
public void GoToNextParagraph(ref Word.Paragraph para,ref object count)
{
para.Next(ref count) ;
}
/**//// <summary>
/// 向前定位到指定段落
/// </summary>
/// <param name="para"></param>
/// <param name="count"></param>
public void GoToPreviousParagraph( ref Word.Paragraph para, ref object count )
{
para.Previous( ref count ) ;
}
public void GoToTheTable( int ntable )
{
object missing = System.Reflection.Missing.Value;
object what;
what = Word.WdUnits.wdTable ;
object which;
which = Word.WdGoToDirection.wdGoToFirst;
object count;
count = 1 ;
oWordApplic.Selection.GoTo( ref what, ref which, ref count, ref missing );
}
public void GoToRightCell( )
{
object missing = System.Reflection.Missing.Value;
object direction;
direction = Word.WdUnits.wdCell;
oWordApplic.Selection.MoveRight( ref direction, ref missing, ref missing );
}
public void GoToLeftCell( )
{
object missing = System.Reflection.Missing.Value;
object direction;
direction = Word.WdUnits.wdCell;
oWordApplic.Selection.MoveLeft( ref direction, ref missing, ref missing );
}
public void GoToDownCell( )
{
object missing = System.Reflection.Missing.Value;
object direction;
direction = Word.WdUnits.wdLine;
oWordApplic.Selection.MoveDown( ref direction, ref missing, ref missing );
}
public void GoToUpCell( )
{
object missing = System.Reflection.Missing.Value;
object direction;
direction = Word.WdUnits.wdLine;
oWordApplic.Selection.MoveUp( ref direction, ref missing, ref missing );
}
public Boolean ExecuteReplace( Word.Find find )
{
return ExecuteReplace( find, Word.WdReplace.wdReplaceAll );
}
public Boolean ExecuteReplace( Word.Find find, Object replaceOption )
{
// Simple wrapper around Find.Execute:
Object findText = Type.Missing;
Object matchCase = Type.Missing;
Object matchWholeWord = Type.Missing;
Object matchWildcards = Type.Missing;
Object matchSoundsLike = Type.Missing;
Object matchAllWordForms = Type.Missing;
Object forward = Type.Missing;
Object wrap = Type.Missing;
Object format = Type.Missing;
Object replaceWith = Type.Missing;
Object replace = replaceOption;
Object matchKashida = Type.Missing;
Object matchDiacritics = Type.Missing;
Object matchAlefHamza = Type.Missing;
Object matchControl = Type.Missing;
return find.Execute( ref findText, ref matchCase, ref matchWholeWord,
ref matchWildcards, ref matchSoundsLike, ref matchAllWordForms,
ref forward, ref wrap, ref format, ref replaceWith, ref replace,
ref matchKashida, ref matchDiacritics, ref matchAlefHamza,
ref matchControl );
}
public Boolean ExecuteFind( Word.Find find )
{
return ExecuteFind( find, find.Text, Type.Missing, Type.Missing );
}
public Boolean ExecuteFind( Word.Find find, string strFindText )
{
return ExecuteFind( find, strFindText, Type.Missing, Type.Missing );
}
public Boolean ExecuteFind(
Word.Find find, string strFindText, Object wrapFind, Object forwardFind )
{
// Simple wrapper around Find.Execute:
Object findText ;
Object matchCase = Type.Missing;
Object matchWholeWord = Type.Missing;
Object matchWildcards = Type.Missing;
Object matchSoundsLike = Type.Missing;
Object matchAllWordForms = Type.Missing;
Object forward = forwardFind;
Object wrap = wrapFind;
Object format = Type.Missing;
Object replaceWith = Type.Missing;
Object replace = Type.Missing;
Object matchKashida = Type.Missing;
Object matchDiacritics = Type.Missing;
Object matchAlefHamza = Type.Missing;
Object matchControl = Type.Missing;
if ( ( strFindText == "" )||( strFindText == string.Empty ) )
findText = find.Text;
else
findText = strFindText;
find.ClearFormatting();
return find.Execute( ref findText, ref matchCase, ref matchWholeWord,
ref matchWildcards, ref matchSoundsLike, ref matchAllWordForms,
ref forward, ref wrap, ref format, ref replaceWith, ref replace,
ref matchKashida, ref matchDiacritics, ref matchAlefHamza,
ref matchControl );
}
public Boolean FindInSelection( Word.Selection Selection, string strFindText )
{
return this.ExecuteFind( Selection.Find,strFindText,System.Type.Missing,System.Type.Missing );
}
public Boolean FindInSelection( Word.Selection Selection, string strFindText, Object wrapFind, Object forwardFind )
{
return this.ExecuteFind( Selection.Find, strFindText, wrapFind, forwardFind );
}
public Boolean FindInRange( Word.Range range,string strFindText )
{
Boolean blnReturn =this.ExecuteFind( range.Find, strFindText, Type.Missing, Type.Missing );
range.Select();
return blnReturn;
}
public void FindInAllDocument( string strFindText )
{
int intFound = 0;
Object start = 0;
Object end = this.oDoc.Characters.Count;
Word.Range rngDoc = oDoc.Range( ref start, ref end );
Word.Find fnd = rngDoc.Find;
fnd.ClearFormatting();
fnd.Forward = true;
fnd.Text = strFindText;
ExecuteFind( fnd );
while ( fnd.Found )
{
rngDoc.Font.Color = Word.WdColor.wdColorRed;
rngDoc.Font.Bold = 600;
intFound++;
ExecuteFind( fnd );
}
MessageBox.Show( String.Format( "lorem found {0} times.", intFound ), "FindInLoopAndFormat" );
}
#endregion
}
}