使用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 ...
随机推荐
- php全局变量漏洞 $GLOBALS
在Discuz代码中有这么一段: if (isset($_REQUEST[‘GLOBALS’]) OR isset($_FILES[‘GLOBALS’])) { exit(‘Request tain ...
- 就这么简单!构建强大的WebShell防护体系
接触web安全中,例如上传一句话WebShell实现上传文件的功能,再通过上传的多功能WebShell,执行病毒文件最终创建远程连接账号,达到入侵目标服务器的效果.我们可以看到,webshell在整个 ...
- mysql 查看索引
查看索引 mysql> show index from tblname; mysql> show keys from tblname; · Table 表的名称. · Non_unique ...
- C语言数据结构之二叉树的实现
本篇博文是博主在学习C语言算法与数据结构的一些应用代码实例,给出了以二叉链表的形式实现二叉树的相关操作.如创建,遍历(先序,中序后序遍历),求树的深度,树的叶子节点数,左右兄弟,父节点. 代码清单如下 ...
- Laravel - 从百草园到三味书屋 "From Apprentice To Artisan"目录
Laravel - 从百草园到三味书屋 "From Apprentice To Artisan"目录 https://my.oschina.net/zgldh/blog/38924 ...
- 题目1001:A+B for Matrices(简单循环)
问题来源 http://ac.jobdu.com/problem.php?pid=1001 问题描述 给你两个形式相同的矩阵,对应位置相加得到新矩阵,计算里面全为0的行数和列数. 问题分析 这里其实只 ...
- [LibreOJ #2341]【WC2018】即时战略【交互】【LCT】
Description 有一棵n个点的结构未知的树,初始时只有1号点是已被访问的. 你可以调用交互库的询问函数explore(x,y),其中x是已访问的点,y是任意点. 它会返回x向y方向走第一步的点 ...
- Mac下一台电脑管理多个SSH KEY(转)
一.关于ssh是什么? http://www.ruanyifeng.com/blog/2011/12/ssh_remote_login.html 二.需求: 一台电脑上(Mac os)管理多个ssh ...
- 窗口大小调整后处理事件jQuery插件ResizeEnd
需要引入的文件: <script src="js/jquery.min.js"></script> <script src="js/jQue ...
- C 标准库 - ctype.h之iscntrl 使用
iscntrl int iscntrl ( int c ); Check if character is a control character 检查给定字符是否为控制字符,即编码 0x00-0x1F ...