Dotnet操作Word与Excel

最近写温泉街道门店管理系统,用到了Word和Excel操作,查了些资料并做了些修改,把两个类的代码放上:

 

Word操作
using System;
using System.ComponentModel;
using System.Data;
using System.Windows.Forms;
using Word = Microsoft.Office.Interop.Word;

namespace StreetControlSystem.Office
{
    
public class WordAdapt
    {
        
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 WordAdapt()
        {
            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;
                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, ref missing);
                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;
                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);
                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, 202000"华文仿宋");
        }

        
/**/
        
/// <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 == nullreturn 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 == nullreturn result;
            
if (strFileName == null || strFileName == ""return result;
            
if (this.Open())
            {
                
try
                {
                    Word.Range para 
= oWordApplic.Application.Selection.Paragraphs[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[
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[
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(string strOld, string strNew)
        {
            Object findText 
= strOld;
            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 
= strNew;
            Object replace 
= Word.WdReplace.wdReplaceAll;
            Object matchKashida 
= Type.Missing;
            Object matchDiacritics 
= Type.Missing;
            Object matchAlefHamza 
= Type.Missing;
            Object matchControl 
= Type.Missing;

            
return oDoc.Content.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 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
    }
}

 

 

Excel操作
using System;
using System.Data;
using System.Configuration;
using Microsoft.Office.Interop;
using Excel = Microsoft.Office.Interop.Excel;
using Microsoft.Office.Core;
using Microsoft.Office;

namespace StreetControlSystem.Office
{
    
/// <SUMMARY>
    
/// ExcelEdit 的摘要说明
    
/// </SUMMARY>
    public class ExcelAdapt
    {
        
public string mFilename;
        
public Excel.Application app;
        
public Excel.Workbooks wbs;
        
public Excel.Workbook wb;
        
public Excel.Worksheets wss;
        
public Excel.Worksheet ws;
        
public ExcelAdapt()
        {
            
//
            
// TODO: 在此处添加构造函数逻辑
            
//
        }
        
public void Create()//创建一个Excel对象
        {
            app 
= new Excel.Application();
            wbs 
= app.Workbooks;
            wb 
= wbs.Add(true);
        }
        
public void Open(string FileName)//打开一个Excel文件
        {
            app 
= new Excel.Application();
            wbs 
= app.Workbooks;
            wb 
= wbs.Add(FileName);
            
//wb = wbs.Open(FileName, 0, true, 5,"", "", true, Excel.XlPlatform.xlWindows, "t", false, false, 0, true,Type.Missing,Type.Missing);
            
//wb = wbs.Open(FileName,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Excel.XlPlatform.xlWindows,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing);
            mFilename = FileName;
        }
        
public Excel.Worksheet GetSheet(string SheetName)
        
//获取一个工作表
        {
            Excel.Worksheet s 
= (Excel.Worksheet)wb.Worksheets[SheetName];
            
return s;
        }
        
public Excel.Worksheet AddSheet(string SheetName)
        
//添加一个工作表
        {
            Excel.Worksheet s 
= (Excel.Worksheet)wb.Worksheets.Add(Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            s.Name 
= SheetName;
            
return s;
        }

        
public void DelSheet(string SheetName)//删除一个工作表
        {
            ((Excel.Worksheet)wb.Worksheets[SheetName]).Delete();
        }
        
public Excel.Worksheet ReNameSheet(string OldSheetName, string NewSheetName)//重命名一个工作表一
        {
            Excel.Worksheet s 
= (Excel.Worksheet)wb.Worksheets[OldSheetName];
            s.Name 
= NewSheetName;
            
return s;
        }

        
public Excel.Worksheet ReNameSheet(Excel.Worksheet Sheet, string NewSheetName)//重命名一个工作表二
        {

            Sheet.Name 
= NewSheetName;

            
return Sheet;
        }

        
public void SetCellValue(Excel.Worksheet ws, int x, int y, object value)
        
//ws:要设值的工作表     X行Y列     value   值
        {
            ws.Cells[x, y] 
= value;
        }
        
public void SetCellValue(string ws, int x, int y, object value)
        
//ws:要设值的工作表的名称 X行Y列 value 值
        {

            GetSheet(ws).Cells[x, y] 
= value;
        }

        
public object GetCellValue(string ws, int x, int y)
        {
            
return GetSheet(ws).Cells[x, y];
        }

        
public object GetCellValue(Excel.Worksheet ws, int x, int y)
        {
            
return ws.Cells[x, y];
        }

        
public void SetCellProperty(Excel.Worksheet ws, int Startx, int Starty, int Endx, int Endy, int size, string name, Excel.Constants color, Excel.Constants HorizontalAlignment)
        
//设置一个单元格的属性   字体,   大小,颜色   ,对齐方式
        {
            name 
= "宋体";
            size 
= 12;
            color 
= Excel.Constants.xlAutomatic;
            HorizontalAlignment 
= Excel.Constants.xlRight;
            ws.get_Range(ws.Cells[Startx, Starty], ws.Cells[Endx, Endy]).Font.Name 
= name;
            ws.get_Range(ws.Cells[Startx, Starty], ws.Cells[Endx, Endy]).Font.Size 
= size;
            ws.get_Range(ws.Cells[Startx, Starty], ws.Cells[Endx, Endy]).Font.Color 
= color;
            ws.get_Range(ws.Cells[Startx, Starty], ws.Cells[Endx, Endy]).HorizontalAlignment 
= HorizontalAlignment;
        }

        
public void SetCellProperty(string wsn, int Startx, int Starty, int Endx, int Endy, int size, string name, Excel.Constants color, Excel.Constants HorizontalAlignment)
        {
            
//name = "宋体";
            
//size = 12;
            
//color = Excel.Constants.xlAutomatic;
            
//HorizontalAlignment = Excel.Constants.xlRight;

            Excel.Worksheet ws 
= GetSheet(wsn);
            ws.get_Range(ws.Cells[Startx, Starty], ws.Cells[Endx, Endy]).Font.Name 
= name;
            ws.get_Range(ws.Cells[Startx, Starty], ws.Cells[Endx, Endy]).Font.Size 
= size;
            ws.get_Range(ws.Cells[Startx, Starty], ws.Cells[Endx, Endy]).Font.Color 
= color;

            ws.get_Range(ws.Cells[Startx, Starty], ws.Cells[Endx, Endy]).HorizontalAlignment 
= HorizontalAlignment;
        }


        
public void UniteCells(Excel.Worksheet ws, int x1, int y1, int x2, int y2)
        
//合并单元格
        {
            ws.get_Range(ws.Cells[x1, y1], ws.Cells[x2, y2]).Merge(Type.Missing);
        }

        
public void UniteCells(string ws, int x1, int y1, int x2, int y2)
        
//合并单元格
        {
            GetSheet(ws).get_Range(GetSheet(ws).Cells[x1, y1], GetSheet(ws).Cells[x2, y2]).Merge(Type.Missing);

        }


        
public void InsertTable(System.Data.DataTable dt, string ws, int startX, int startY)
//将内存中数据表格插入到Excel指定工作表的指定位置 为在使用模板时控制格式时使用一
        {

            
for (int i = 0; i <= dt.Rows.Count - 1; i++)
            {
                
for (int j = 0; j <= dt.Columns.Count - 1; j++)
                {
                    GetSheet(ws).Cells[startX
+i, j + startY] = dt.Rows[i][j].ToString();

                }

            }

        }
        
public void InsertTable(System.Data.DataTable dt, Excel.Worksheet ws, int startX, int startY)
//将内存中数据表格插入到Excel指定工作表的指定位置二
        {

            
for (int i = 0; i <= dt.Rows.Count - 1; i++)
            {
                
for (int j = 0; j <= dt.Columns.Count - 1; j++)
                {

                    ws.Cells[startX
+i, j + startY] = dt.Rows[i][j];

                }

            }

        }


        
public void AddTable(System.Data.DataTable dt, string ws, int startX, int startY)
//将内存中数据表格添加到Excel指定工作表的指定位置一
        {

            
for (int i = 0; i <= dt.Rows.Count - 1; i++)
            {
                
for (int j = 0; j <= dt.Columns.Count - 1; j++)
                {

                    GetSheet(ws).Cells[i 
+ startX, j + startY] = dt.Rows[i][j];

                }

            }

        }
        
public void AddTable(System.Data.DataTable dt, Excel.Worksheet ws, int startX, int startY)
//将内存中数据表格添加到Excel指定工作表的指定位置二
        {


            
for (int i = 0; i <= dt.Rows.Count - 1; i++)
            {
                
for (int j = 0; j <= dt.Columns.Count - 1; j++)
                {

                    ws.Cells[i 
+ startX, j + startY] = dt.Rows[i][j];

                }
            }

        }

        
public void CopyToTable(ref DataTable dt, Excel.Worksheet ws, int startX, int startY, int width, int height)
        {
            
object[] objs = new object[width];
            
for (int r = 0; r < height; r++)
            {
                
for (int i = 0; i < width; i++)
                {
                    objs[i] 
= ws.Cells[startX + i, startY + r];
                }
                dt.Rows.Add(objs);
            }
        }

        
//public void InsertPictures(string Filename, string ws)
        ////插入图片操作一
        //{
        
//    GetSheet(ws).Shapes.AddPicture(Filename, MsoTriState.msoTrue, MsoTriState.msoTrue, 10F, 10F, 150F, 150F);
        
//    //后面的数字表示位置
        
//}

        
//public void InsertPictures(string Filename, string ws, int Height, int Width)
        
//插入图片操作二
        
//{
        
//    GetSheet(ws).Shapes.AddPicture(Filename, MsoTriState.msoFalse, MsoTriState.msoTrue, 10, 10, 150, 150);
        
//    GetSheet(ws).Shapes.get_Range(Type.Missing).Height = Height;
        
//    GetSheet(ws).Shapes.get_Range(Type.Missing).Width = Width;
        
//}
        
//public void InsertPictures(string Filename, string ws, int left, int top, int Height, int Width)
        
//插入图片操作三
        
//{

        
//    GetSheet(ws).Shapes.AddPicture(Filename, MsoTriState.msoFalse, MsoTriState.msoTrue, 10, 10, 150, 150);
        
//    GetSheet(ws).Shapes.get_Range(Type.Missing).IncrementLeft(left);
        
//    GetSheet(ws).Shapes.get_Range(Type.Missing).IncrementTop(top);
        
//    GetSheet(ws).Shapes.get_Range(Type.Missing).Height = Height;
        
//    GetSheet(ws).Shapes.get_Range(Type.Missing).Width = Width;
        
//}

        
public void InsertActiveChart(Excel.XlChartType ChartType, string ws, int DataSourcesX1, int DataSourcesY1, int DataSourcesX2, int DataSourcesY2, Excel.XlRowCol ChartDataType)
        
//插入图表操作
        {
            ChartDataType 
= Excel.XlRowCol.xlColumns;
            wb.Charts.Add(Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            {
                wb.ActiveChart.ChartType 
= ChartType;
                wb.ActiveChart.SetSourceData(GetSheet(ws).get_Range(GetSheet(ws).Cells[DataSourcesX1, DataSourcesY1], GetSheet(ws).Cells[DataSourcesX2, DataSourcesY2]), ChartDataType);
                wb.ActiveChart.Location(Excel.XlChartLocation.xlLocationAsObject, ws);
            }
        }
        
public bool Save()
        
//保存文档
        {
            
if (mFilename == "")
            {
                
return false;
            }
            
else
            {
                
try
                {
                    wb.Save();
                    
return true;
                }

                
catch
                {
                    
return false;
                }
            }
        }
        
public bool SaveAs(object FileName)
        
//文档另存为
        {
            
try
            {
                wb.SaveAs(FileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
                
return true;

            }

            
catch
            {
                
return false;

            }
        }
        
public void Close()
        
//关闭一个Excel对象,销毁对象
        {
            
//wb.Save();
            wb.Close(Type.Missing, Type.Missing, Type.Missing);
            wbs.Close();
            app.Quit();
            wb 
= null;
            wbs 
= null;
            app 
= null;
            GC.Collect();
        }
    }
}

 

 

posted on 2010-07-22 00:41  寻雨  阅读(436)  评论(0编辑  收藏  举报

导航