使用word的com組件解決讀取時亂碼的問題

使用流讀取word會產生亂碼
HttpPostedFile myFile=this.ContentFile.PostedFile;
System.IO.Stream myStream=myFile.InputStream;
System.IO.StreamReader myStreamReader=
          new System.IO.StreamReader(myStream,System.Text.Encoding.GetEncoding("GB2312"));
string myString=myStreamReader.ReadToEnd();

此時myString就成亂碼了
這樣System.IO.StreamReader myStreamReader=
          new System.IO.StreamReader(myStream,System.Text.Encoding.Default);
也是亂碼,但是可以正確讀取text文件。
後來根據word可以轉換爲html的思路,想了另外一個辦法,把word上傳到服務器,轉換爲text,然後讀取text。
    調試通過的 代碼如下:
//上傳文件
HttpPostedFile ContentFile=this.ContentFile.PostedFile;
string ContentName=System.IO.Path.GetFileName(ContentFile.FileName);
     string ContentPath=Request.MapPath("/web/uploadDocs/"+ContentName);
     ContentFile.SaveAs(ContentPath);
     string NewContentPath=System.IO.Path.ChangeExtension(ContentPath,"txt");

//轉換word爲text

     WordXpControl.WordControler UploadWord=new WordXpControl.WordControler();
     UploadWord.Open(ContentPath);
     UploadWord.SaveAsExportTye(NewContentPath,WordXpControl.WordControler.ExportType.Text);
     UploadWord.Quit();

//讀取對應的text文件

                    System.IO.StreamReader myReader=new System.IO.StreamReader(NewContentPath,System.Text.Encoding.Default);
     strContent=myReader.ReadToEnd();
     myReader.Close();
     strContent=ManageProcess.GetFormatedString(strContent);

//根據需要決定是否刪除上傳的word文件和對應的text文件
     if(this.CbIsDelete.Checked)
     {
      System.IO.File.Delete(ContentPath);
      System.IO.File.Delete(NewContentPath);

     }



上面的WordXpControl是前不久封裝的對word操作的程序集,方面對word的操作。使用前要引用Microsoft Word 10 Object Library,然後再引用該程序集即可。通過ExportType枚舉可以決定轉換的類型,如:html。也可進行一些其他操作。該程序集核心代碼來自網上,很多功能本人也未嘗使用。



以上代碼都是在vs2003,win2000,officeXp上調試運行,對於其他版本可能有問題。office2000在孟子的網站上有成功例子。注意給asp.net進程指定system權限運行,以免出現權限不夠的異常。



由於這裏不能上傳,最後給出WordXpControl的代碼,編譯以後即可使用:
using System;

 

namespace WordXpControl
{
 /// <summary>
 /// WordXPControl 的摘要說明。
 /// </summary>
 public class WordControler
 {
  public WordControler()
  {
   //
   // TODO: 在此處添加構造函數邏輯
   //
   oWordApplic = new Word.ApplicationClass();
  }

  private Word.ApplicationClass oWordApplic; // a reference to Word application
  private Word.Document oDoc;     // a reference to the document
  

  
  public void Open( string strFileName)
  {
   object fileName = strFileName;
   object;
   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);

   oDoc.Activate();  
   
  }  


  
  public void Open( )
  {
   object missing = System.Reflection.Missing.Value;
   oDoc = oWordApplic.Documents.Add(ref missing, ref missing,ref missing, ref missing);

   oDoc.Activate();   
  }  

 


  public void Quit( )
  {
   object missing = System.Reflection.Missing.Value;
   oWordApplic.Application.Quit(ref missing, ref missing, ref missing); 
  }  

  public void Save( )
  {
   oDoc.Save();   
  }  

  public void SaveAs(string strFileName )
  {
   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);
  }  
 
  //根據傳入的類型(ExportType枚舉的值)保存文件
  public void SaveAsExportTye(string strFileName,ExportType exportType)
  {
   object missing = System.Reflection.Missing.Value;
   object fileName = strFileName;
   object Format = exportType;
   oDoc.SaveAs(ref fileName, ref Format,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);
   oDoc.Close(ref missing ,ref missing,ref missing);
     
  }

  public void CopyAll()
  {
   oWordApplic.Selection.WholeStory();
   oWordApplic.Selection.Copy();
   
  }
  public void PasetAll()
  {
  
   oWordApplic.Selection.PasteAndFormat(Word.WdRecoveryType.wdPasteDefault);
   

  }
  public void Clear()
  {
        
   object Unit=(int)Word.WdUnits.wdCharacter;
   object Count=1;
   oWordApplic.Selection.WholeStory();
   oWordApplic.Selection.Delete(ref Unit,ref Count);
  }

 

  public void InsertText( string strText)
  {
   oWordApplic.Selection.TypeText(strText);
  }

  public void InsertLineBreak( )
  {
   oWordApplic.Selection.TypeParagraph();
  }
  public void InsertLineBreak( int nline)
  {
   for (int i=0; i<nline; i++)
    oWordApplic.Selection.TypeParagraph();
  }

  
  public void SetAlignment(string strType )
  {
   switch (strType)
   {
    case "Center" :
     oWordApplic.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
     break;
    case "Left" :
     oWordApplic.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
     break;
    case "Right" :
     oWordApplic.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;
     break;
    case "Justify" :
     oWordApplic.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphJustify;
     break;
   }
 
  }


  
  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;
   }
   
  }
  
  
  public void SetFont( )
  {
   oWordApplic.Selection.Font.Bold = 0;
   oWordApplic.Selection.Font.Italic = 0;
   oWordApplic.Selection.Font.Subscript = 0;
  
  }

  public void SetFontName( string strType )
  {
   oWordApplic.Selection.Font.Name = strType;
   
  }

  public void SetFontSize( int nSize )
  {
   oWordApplic.Selection.Font.Size = nSize;
   
  }

  public void InsertPagebreak()
  {
   
   object pBreak= (int)Word.WdBreakType.wdPageBreak;
   oWordApplic.Selection.InsertBreak(ref pBreak );
  }

  

  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);
  }

  public void GoToTheEnd( )
  {
   
   object missing = System.Reflection.Missing.Value;
   object unit ;
   unit = Word.WdUnits.wdStory ;
   oWordApplic.Selection.EndKey ( ref unit, ref missing);
   
  }
  public void GoToTheBeginning( )
  {
   
   object missing = System.Reflection.Missing.Value;
   object unit ;
   unit = Word.WdUnits.wdStory ;
   oWordApplic.Selection.HomeKey ( ref unit, ref missing);
   
  }

  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);
   oWordApplic.Selection.Find.ClearFormatting();

   oWordApplic.Selection.Text = "";
   
   
  }

  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 void InsertPageNumber( string strType, bool bHeader )
  {
   object missing = System.Reflection.Missing.Value;
   object alignment ;
   object bFirstPage = false;
   object bF = true;
   switch (strType)
   {
    case "Center":
     alignment = Word.WdPageNumberAlignment.wdAlignPageNumberCenter;
     oWordApplic.Selection.HeaderFooter.PageNumbers.Item(1).Alignment = Word.WdPageNumberAlignment.wdAlignPageNumberCenter;
     break;
    case "Right":
     alignment = Word.WdPageNumberAlignment.wdAlignPageNumberRight;
     oWordApplic.Selection.HeaderFooter.PageNumbers.Item(1).Alignment = Word.WdPageNumberAlignment.wdAlignPageNumberRight;
     break;
    case "Left":
     alignment = Word.WdPageNumberAlignment.wdAlignPageNumberLeft;
     oWordApplic.Selection.HeaderFooter.PageNumbers.Add(ref alignment,ref bFirstPage);
     break;
   }
           
  }
  
        //建立枚舉和Word.WdSaveFormat中的值對應:如Word.WdSaveFormat.wdFormatHTML;對應於ExportType中的HTML
  public enum ExportType
  {
   Document,
   Template,
   Text,
   TextLineBreaks,
   DOSText,
   DOSTextLineBreaks,
   RTF,
   UnicodeText,
   HTML,
   WebArchive,
   FilteredHTML
  }

 }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章