添加引用ICSharpCode.SharpZipLib.dll、NPOI.dll、NPOI.OOXML.dll、NPOI.OpenXml4Net.dll、NPOI.OpenXmlFormats.dll,这几个dll文件NPOI官网上只能下载到源码,编译有些麻烦。这里找到一个现成的,http://www.itmop.com/downinfo/267826.html。
源码如下。
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using NPOI.XWPF.UserModel;
using System.IO;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
openFileDialog1.Title = "选择word文件";
openFileDialog1.Filter = "Word文档|*.docx";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
textBox1.Text = openFileDialog1.FileName;
}
}
private void button2_Click(object sender, EventArgs e)
{
//遍历word文档所有段落,并存入文本文件
FileStream fs = new FileStream(textBox1.Text, FileMode.Open);
XWPFDocument doc = new XWPFDocument(fs);
IList<XWPFParagraph> paragraphs = doc.Paragraphs;
foreach(XWPFParagraph paragraph in paragraphs)
{
File.AppendAllText("⽂本1.txt", paragraph.Text);
}
}
}
}