C#(1)實現一鍵從Word文檔轉換TXT文本的功能

有想直接從Word轉TXT文本的能夠看看,懶得複製粘貼的也可使用下,方便而快捷!!html

首先打開vs2012建立一個簡單的form窗體:ui

裏面主要的就是一個存放Word文檔的button和一個執行的buttonspa

點擊運行後:把實驗的Word文檔導入文件中:orm

點擊開始轉換的button,進行執行文件:htm

點擊肯定實現整個過程,打開TXT文檔:blog

 核心代碼部分:文檔

namespace WordToText
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        public static void WordToHtmlText(string WordFilePath)
        {
            try
            {
                Word.Application wApp = new Word.Application();
                //指定原文件和目標文件 
                object docPath = WordFilePath;
                string htmlPath = WordFilePath.Substring(0, WordFilePath.Length - 3) + "txt";
                object Target = htmlPath;
                //缺省參數 
                object Unknown = Type.Missing;
                //只讀方式打開 
                object readOnly = true;
                //打開doc文件 
                Word.Document document = wApp.Documents.Open(ref docPath, ref Unknown,
                ref readOnly, ref Unknown, ref Unknown,
                ref Unknown, ref Unknown, ref Unknown,
                ref Unknown, ref Unknown, ref Unknown,
                ref Unknown);
                object format = Word.WdSaveFormat.wdFormatText;
                document.SaveAs(ref Target, ref format,
                ref Unknown, ref Unknown, ref Unknown,
                ref Unknown, ref Unknown, ref Unknown,
                ref Unknown, ref Unknown, ref Unknown); 
                document.Close(ref Unknown, ref Unknown, ref Unknown);
                wApp.Quit(ref Unknown, ref Unknown, ref Unknown);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }
        private void button2_Click(object sender, EventArgs e)
        {
            if (textBox1.Text != "")
            {
                WordToHtmlText(textBox1.Text.Trim());
                MessageBox.Show("轉換成功,在Word文件的同一目錄下可找到TXT數據!");
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
                textBox1.Text = openFileDialog1.FileName;
        }
    }
}

  有興趣的能夠本身動手試試!get

相關文章
相關標籤/搜索