使用NOPI读取Excel的例子很多,读取Word的例子不多。

Excel的解析方式有多中,可以使用ODBC查询,把Excel作为一个数据集对待。也可以使用文档结构模型的方式进行解析,即解析Workbook(工作簿)、Sheet、Row、Column。

Word的解析比较复杂,因为Word的文档结构模型定义较为复杂。解析Word或者Excel,关键是理解Word、Excel的文档对象模型。

Word、Excel文档对象模型的解析,可以通过COM接口调用,此类方式使用较广。(可以录制宏代码,然后替换为对应的语言)

也可以使用XML模型解析,尤其是对于2007、2010版本的文档的解析。

 using NPOI.POIFS.FileSystem;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.XWPF.UserModel;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Text; namespace eyuan
{
public static class NOPIHandler
{
/// <summary>
///
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
public static List<List<List<string>>> ReadExcel(string fileName)
{
//打开Excel工作簿
XSSFWorkbook hssfworkbook = null;
try
{
using (FileStream file = new FileStream(fileName, FileMode.Open, FileAccess.Read))
{
hssfworkbook = new XSSFWorkbook(file);
}
}
catch (Exception e)
{
LogHandler.LogWrite(string.Format("文件{0}打开失败,错误:{1}", new string[] { fileName, e.ToString() }));
}
//循环Sheet页
int sheetsCount = hssfworkbook.NumberOfSheets;
List<List<List<string>>> workBookContent = new List<List<List<string>>>();
for (int i = ; i < sheetsCount; i++)
{
//Sheet索引从0开始
ISheet sheet = hssfworkbook.GetSheetAt(i);
//循环行
List<List<string>> sheetContent = new List<List<string>>();
int rowCount = sheet.PhysicalNumberOfRows;
for (int j = ; j < rowCount; j++)
{
//Row(逻辑行)的索引从0开始
IRow row = sheet.GetRow(j);
//循环列(各行的列数可能不同)
List<string> rowContent = new List<string>();
int cellCount = row.PhysicalNumberOfCells;
for (int k = ; k < cellCount; k++)
{
//ICell cell = row.GetCell(k);
ICell cell = row.Cells[k];
if (cell == null)
{
rowContent.Add("NIL");
}
else
{
rowContent.Add(cell.ToString());
//rowContent.Add(cell.StringCellValue);
}
}
//添加行到集合中
sheetContent.Add(rowContent);
}
//添加Sheet到集合中
workBookContent.Add(sheetContent);
} return workBookContent;
} /// <summary>
///
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
public static string ReadExcelText(string fileName)
{
string ExcelCellSeparator = ConfigurationManager.AppSettings["ExcelCellSeparator"];
string ExcelRowSeparator = ConfigurationManager.AppSettings["ExcelRowSeparator"];
string ExcelSheetSeparator = ConfigurationManager.AppSettings["ExcelSheetSeparator"];
//
List<List<List<string>>> excelContent = ReadExcel(fileName);
string fileText = string.Empty;
StringBuilder sbFileText = new StringBuilder();
//循环处理WorkBook中的各Sheet页
List<List<List<string>>>.Enumerator enumeratorWorkBook = excelContent.GetEnumerator();
while (enumeratorWorkBook.MoveNext())
{ //循环处理当期Sheet页中的各行
List<List<string>>.Enumerator enumeratorSheet = enumeratorWorkBook.Current.GetEnumerator();
while (enumeratorSheet.MoveNext())
{ string[] rowContent = enumeratorSheet.Current.ToArray();
sbFileText.Append(string.Join(ExcelCellSeparator, rowContent));
sbFileText.Append(ExcelRowSeparator);
}
sbFileText.Append(ExcelSheetSeparator);
}
//
fileText = sbFileText.ToString();
return fileText;
} /// <summary>
/// 读取Word内容
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
public static string ReadWordText(string fileName)
{
string WordTableCellSeparator = ConfigurationManager.AppSettings["WordTableCellSeparator"];
string WordTableRowSeparator = ConfigurationManager.AppSettings["WordTableRowSeparator"];
string WordTableSeparator = ConfigurationManager.AppSettings["WordTableSeparator"];
//
string CaptureWordHeader = ConfigurationManager.AppSettings["CaptureWordHeader"];
string CaptureWordFooter = ConfigurationManager.AppSettings["CaptureWordFooter"];
string CaptureWordTable = ConfigurationManager.AppSettings["CaptureWordTable"];
string CaptureWordImage = ConfigurationManager.AppSettings["CaptureWordImage"];
//
string CaptureWordImageFileName = ConfigurationManager.AppSettings["CaptureWordImageFileName"];
//
string fileText = string.Empty;
StringBuilder sbFileText = new StringBuilder(); #region 打开文档
XWPFDocument document = null;
try
{
using (FileStream file = new FileStream(fileName, FileMode.Open, FileAccess.Read))
{
document = new XWPFDocument(file);
}
}
catch (Exception e)
{
LogHandler.LogWrite(string.Format("文件{0}打开失败,错误:{1}", new string[] { fileName, e.ToString() }));
}
#endregion #region 页眉、页脚
//页眉
if (CaptureWordHeader == "true")
{
sbFileText.AppendLine("Capture Header Begin");
foreach (XWPFHeader xwpfHeader in document.HeaderList)
{
sbFileText.AppendLine(string.Format("{0}", new string[] { xwpfHeader.Text }));
}
sbFileText.AppendLine("Capture Header End");
}
//页脚
if (CaptureWordFooter == "true")
{
sbFileText.AppendLine("Capture Footer Begin");
foreach (XWPFFooter xwpfFooter in document.FooterList)
{
sbFileText.AppendLine(string.Format("{0}", new string[] { xwpfFooter.Text }));
}
sbFileText.AppendLine("Capture Footer End");
}
#endregion #region 表格
if (CaptureWordTable == "true")
{
sbFileText.AppendLine("Capture Table Begin");
foreach (XWPFTable table in document.Tables)
{
//循环表格行
foreach (XWPFTableRow row in table.Rows)
{
foreach (XWPFTableCell cell in row.GetTableCells())
{
sbFileText.Append(cell.GetText());
//
sbFileText.Append(WordTableCellSeparator);
} sbFileText.Append(WordTableRowSeparator);
}
sbFileText.Append(WordTableSeparator);
}
sbFileText.AppendLine("Capture Table End");
}
#endregion #region 图片
if (CaptureWordImage == "true")
{
sbFileText.AppendLine("Capture Image Begin");
foreach (XWPFPictureData pictureData in document.AllPictures)
{
string picExtName = pictureData.suggestFileExtension();
string picFileName = pictureData.GetFileName();
byte[] picFileContent = pictureData.GetData();
//
string picTempName = string.Format(CaptureWordImageFileName, new string[] { Guid.NewGuid().ToString() + "_" + picFileName + "." + picExtName });
//
using (FileStream fs = new FileStream(picTempName, FileMode.Create, FileAccess.Write))
{
fs.Write(picFileContent, , picFileContent.Length);
fs.Close();
}
//
sbFileText.AppendLine(picTempName);
}
sbFileText.AppendLine("Capture Image End");
}
#endregion //正文段落
sbFileText.AppendLine("Capture Paragraph Begin");
foreach (XWPFParagraph paragraph in document.Paragraphs)
{
sbFileText.AppendLine(paragraph.ParagraphText); }
sbFileText.AppendLine("Capture Paragraph End");
// //
fileText = sbFileText.ToString();
return fileText;
} }
}

使用NOPI读取Word、Excel文档内容的更多相关文章

  1. Oracle PLSQL读取(解析)Excel文档

    http://www.itpub.net/thread-1921612-1-1.html !!!https://code.google.com/p/plsql-utils/ Introduction介 ...

  2. php创建读取 word.doc文档

    创建文档; <?php $html = "this is question"; for($i=1;$i<=3;$i++){ $word = new word(); $w ...

  3. Word/Excel文档伪装病毒-kspoold.exe分析

    一. 病毒样本基本信息 样本名称:kspoold.exe 样本大小: 285184 字节 样本MD5:CF36D2C3023138FE694FFE4666B4B1B2 病毒名称:Win32/Troja ...

  4. php读取excel文档内容(转载)

    入到数据库的需要,php-excel-reader可以很轻松的使用它读取excel文件,本文将详细介绍,需要了解的朋友可以参考下   php开发中肯定会遇到将excel文件内容导入到数据库的需要,ph ...

  5. Python比较两个excel文档内容的异同

    #-*- coding: utf-8 -*- #比对两个Excel文件内容的差异#---------------------假设条件----------------#1.源表和目标表格式一致#2.不存 ...

  6. PowerDesigner 125 导致 Word 2007文档内容无法选中以及点击鼠标没用

  7. java操作office和pdf文件java读取word,excel和pdf文档内容

    在平常应用程序中,对office和pdf文档进行读取数据是比较常见的功能,尤其在很多web应用程序中.所以今天我们就简单来看一下Java对word.excel.pdf文件的读取.本篇博客只是讲解简单应 ...

  8. php 如何写入、读取word,excel文档

    如何在php写入.读取word文档 <? //如何在php写入.读取word文档 // 建立一个指向新COM组件的索引 $word = new COM("word.applicatio ...

  9. ASP 读取Word文档内容简单示例

    以下通过Word.Application对象来读取Doc文档内容并显示示例. 下面进行注册Word组件:1.将以下代码存档命名为:AxWord.wsc XML code复制代码 <?xml ve ...

随机推荐

  1. Linux 解压 压缩文件

    来源于:http://blog.csdn.net/mmllkkjj/article/details/6768294/ 解压 tar –xvf file.tar //解压 tar包tar -xzvf f ...

  2. mxonline实战10,课程列表页,课程详情页1

    对应github地址:第10天   一. 课程列表页   1. 拷贝course-list.html到templates目录中 2. 编写url和view 在courses/views.py中新加

  3. Settings app简单学习记录

    Settings是android系统设置的入口.主界面由Settings.java以及settings_headers.xml构成. Settings类继承自PreferenceActivity,而P ...

  4. clang命令理解程序

    Xcode 创建一个mac OS   command Line Tool程序 步骤打开终端  cd + 工程路径(绝对路径)(注:拖拽main.m文件到终端) input —preprocessor— ...

  5. ORACLE Sequence 自增长

    Sequence是数据库系统按照一定规则自动增加的数字序列.这个序列一般作为代理主键(因为不会重复),没有其他任何意义. Sequence是数据库系统的特性,有的数据库有Sequence,有的没有.比 ...

  6. canvas+js画饼状图

    效果: 源码: <!DOCTYPE html> <html lang="en"> <head> <meta charset="U ...

  7. TX2 之tensorflow环境部署

    刷机jetpack3.3 首先TX2必须是3.3版本的jetpack,因为截止目前nvidia发布的tensorflow只支持3.3版本的jetpack,刷机的具体步骤可以参考NVIDIA Jetso ...

  8. 任务调度SpringTask

    一.什么是任务调度 在企业级应用中,经常会制定一些“计划任务”,即在某个时间点做某件事情,核心是以时间为关注点,即在一个特定的时间点,系统执行指定的一个操作.常见的任务调度框架有Quartz和Spri ...

  9. 【文档】三、Mysql Binlog事件类文件和类型

    在内部,服务器使用C++类文件来表示binlog事件.标准在log_event.h文件中,这些类的方法代码在log_event.cc中. log_event是基础类.其他的详细的事件子类都是来源于他. ...

  10. redis 数据持久化 aof方式

    redis持久化-Append-only file(缩写aof)的方式 本质:把用户执行的每个  ”写“ 指令(增加.修改.删除)都备份到文件中,还原数据的时候就是执行具体写指令. 打开redis的运 ...