/// <summary>
/// 获取.docx文件内容,使用NPOI.XWPF插件解析
/// </summary>
/// <param name="strFilePath">文件路径</param>
/// <returns></returns>
public string GetDocxContent(string wordFilePath)
{
var sb = new StringBuilder();
try
{
//var wordFilePath = Path.Combine(Application.StartupPath, "1.docx");
Stream stream = File.OpenRead(wordFilePath);
XWPFDocument doc = new XWPFDocument(stream);
foreach (var para in doc.Paragraphs)
{
string text = para.ParagraphText; //获得文本
if (text.Trim() != "")
sb.AppendLine(text);
}
}
catch (Exception e)
{
}
var str = sb.ToString();
return str;
}
private void button1_Click(object sender, EventArgs e)
{
try
{
IWorkbook workbook = new XSSFWorkbook();
var sheet = workbook.CreateSheet("sheet1");
#region 写入excel
var wordFilePath = Path.Combine(Application.StartupPath, "1.txt");
var str = File.ReadAllLines(wordFilePath);
var i=0;
foreach (string s in str)
{
var txt = s.Trim();
if (txt != "")
{
if (!txt.StartsWith("("))
{
var row= sheet.CreateRow(i);
i++;
var cell = row.CreateCell(0);
cell.SetCellValue(txt);
}
else
{
}
}
}
string targetFile = Path.Combine(Application.StartupPath, "1.xlsx");
var file = new FileStream(targetFile, FileMode.Create, FileAccess.Write);
workbook.Write(file);
file.Close();
workbook.Close();
MessageBox.Show("ok");
#endregion
}
catch (Exception ex)
{
File.AppendAllText("log.txt",ex.Message+"\r\n");
MessageBox.Show(ex.Message);
}
}