第一步引入COM组件
第二步,引入命名空间
using Microsoft.Office.Interop.Word;
第三步:代码
private void button2_Click(object sender, EventArgs e) { try { //获取Excel文件路径和名称 OpenFileDialog odXls = new OpenFileDialog(); // 指定相应的打开文档的目录 odXls.InitialDirectory = "C:\\"; // 设置文件格式 odXls.Filter = "记事本(*.txt)|*.txt|Word文档(*.doc)|*doc"; odXls.FilterIndex = 2; odXls.RestoreDirectory = true; if (odXls.ShowDialog() == DialogResult.OK) { //以下注释为读取txt不能读取word //StreamReader streamopen = new StreamReader(odXls.FileName, System.Text.Encoding.Default); //textBox1.Text = streamopen.ReadToEnd(); //streamopen.Close(); readFileContent(odXls.FileName); } } catch (Exception Ex) { MessageBox.Show(Ex.Message); } } // 读取word private void readFileContent(string path) { Microsoft.Office.Interop.Word.ApplicationClass wordApp = new ApplicationClass(); object file = path; object nullobj = System.Reflection.Missing.Value; Microsoft.Office.Interop.Word.Document doc = wordApp.Documents.Open( ref file, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj); doc.ActiveWindow.Selection.WholeStory(); doc.ActiveWindow.Selection.Copy(); IDataObject data = Clipboard.GetDataObject(); textBox1.Text = data.GetData(DataFormats.Text).ToString(); doc.Close(ref nullobj, ref nullobj, ref nullobj); wordApp.Quit(ref nullobj, ref nullobj, ref nullobj); }
- 本文标题: Winform如何读取word没有乱码
- 文章分类:【WinForm/WPF】
- 非特殊说明,本文版权归【胡同里的砖头】个人博客 所有,转载请注明出处.