使用NOPI读取Word、Excel文档内容
使用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文档内容的更多相关文章
- Oracle PLSQL读取(解析)Excel文档
http://www.itpub.net/thread-1921612-1-1.html !!!https://code.google.com/p/plsql-utils/ Introduction介 ...
- php创建读取 word.doc文档
创建文档; <?php $html = "this is question"; for($i=1;$i<=3;$i++){ $word = new word(); $w ...
- Word/Excel文档伪装病毒-kspoold.exe分析
一. 病毒样本基本信息 样本名称:kspoold.exe 样本大小: 285184 字节 样本MD5:CF36D2C3023138FE694FFE4666B4B1B2 病毒名称:Win32/Troja ...
- php读取excel文档内容(转载)
入到数据库的需要,php-excel-reader可以很轻松的使用它读取excel文件,本文将详细介绍,需要了解的朋友可以参考下 php开发中肯定会遇到将excel文件内容导入到数据库的需要,ph ...
- Python比较两个excel文档内容的异同
#-*- coding: utf-8 -*- #比对两个Excel文件内容的差异#---------------------假设条件----------------#1.源表和目标表格式一致#2.不存 ...
- PowerDesigner 125 导致 Word 2007文档内容无法选中以及点击鼠标没用
- java操作office和pdf文件java读取word,excel和pdf文档内容
在平常应用程序中,对office和pdf文档进行读取数据是比较常见的功能,尤其在很多web应用程序中.所以今天我们就简单来看一下Java对word.excel.pdf文件的读取.本篇博客只是讲解简单应 ...
- php 如何写入、读取word,excel文档
如何在php写入.读取word文档 <? //如何在php写入.读取word文档 // 建立一个指向新COM组件的索引 $word = new COM("word.applicatio ...
- ASP 读取Word文档内容简单示例
以下通过Word.Application对象来读取Doc文档内容并显示示例. 下面进行注册Word组件:1.将以下代码存档命名为:AxWord.wsc XML code复制代码 <?xml ve ...
随机推荐
- 哈工大ComingX-创新工场俱乐部正式成立
当我把这两个Logo放在一起的时候,我有一种感觉,这种感觉同样存在于ComingX队员的心中.大学我们走到了一起,非你我所预料,却又如此自然.在感恩节的零点,我迫不及待地告诉各位ComingX队员和关 ...
- java简单工厂设计模式
一.基本定义 /* *简单工厂设计模式: *文字描述理解: * 简单工厂模式属于类的创建型模式,又叫做静态工厂方法模式. * 通过专门定义一个类来负责创建其它类的实例,被创建的实例通常 * 都具有共同 ...
- 使用sourceTree需要注意的地方
1.使用CocoaPods 管理第三方库的时候,需要注意不要把Pod文件夹上传到版本管理服务器中 2.使用xcdoe的时候,还有一些个人用户数据也不要上传,可有效避免冲突的发生频率 3.团队开发的时候 ...
- FlowPortal-BPM——创建新组织架构、表单、流程
一.创建新组织架构 (1)管理流程→组织管理→组织架构添加需要的组织架构→新建新成员或角色 (2)设置成员信息 二.创建新数据源(如果在已有的数据库中操作,只需要添加需要的表) (1)添加新数据库并添 ...
- python3.6的request
request实例1: import requests payload = {'key1':'value','key2':'value2'} url = "http://httpbin.or ...
- [转] Linux History(历史)命令用法 15 例
[From]https://linuxtoy.org/archives/history-command-usage-examples.html 如果你经常使用 Linux 命令行,那么使用 histo ...
- android中画弧函数canvas.drawArc()之理解
在学习android中图形图像处理技术这部分内容时,对绘制圆弧函数canvas.drawArc()的用法.参数含义及画图原理很是不理解,在网上搜索了一些,加上自己的理解,在此做个小总结,作为学习过程中 ...
- WCF系列教程之WCF中的会话
本文参考自http://www.cnblogs.com/wangweimutou/p/4516224.html,纯属读书笔记,加深记忆 一.WCF会话简介 1.在WCF应用程序中,回话将一组消息相互关 ...
- ubuntu apache2 .htaccess 下配置 反向代理
安装完apache2后, a2enmod rewrite //启用.htaccess规则 a2enmod proxy a2enmod proxy_http //启用反向代理支持 [P] 配置OK,就可 ...
- str_split 分隔中文出现乱码 替代函数
function mbstringtoarray($str,$charset) { $strlen=mb_strlen($str); while($strlen){ $array[]=mb_subst ...