使用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 ...
随机推荐
- USB-Redirector-Technician 永久破解版(USB设备映射软件)
USB-Redirector-Technician 这个软件对于搞安卓刷机的人想必非常熟悉,淘宝破解版售价:38 一个的东西 除了远程刷机,用于映射一些小型设备是没问题的,只要网跟得上~ USB-Re ...
- Markdown入门简介
参考 http://sspai.com/25137 作者: Te_Lee 文章来源: 少数派 Markdown入门简介(使用工具Haroopad) 一.使用的工具----haroopad(http:/ ...
- tf入门-卷积步长strides参数的具体解释
conv1 = tf.nn.conv2d(input_tensor,conv1_weights,strides=[1,1,1,1],padding='SAME') 这是一个常见的卷积操作,其中stri ...
- 前端IDE:VSCode + WebStorm
VSCode 插件安装 官网:Extensions for the Visual Studio family of products: (1)拼接下载链接: https://${publisher}. ...
- 编程开发之--java多线程学习总结(3)类锁
2.使用方法同步 package com.lfy.ThreadsSynchronize; /** * 1.使用同步方法 * 语法:即用 synchronized 关键字修饰方法(注意是在1个对象中用锁 ...
- ubuntu14 安装tftp服务器
安装 sudo apt-get install tftp-hpa tftpd-hpa 配置 sudo gedit /etc/default/tftpd-hpa 打开tftpd-hpa修改里面的配置: ...
- 多线程atomicInteger
并发编程的3个重要概念 1.原子性: 一个操作或者多个操作,要么全部成功,要么全部失败 1.java中保证了基本数据类型的读取和赋值,保证了原子性,这些操作不可终端 a=10 原子性 b=a 不满足 ...
- springmvc 运行原理 Spring ioc的实现原理 Mybatis工作流程 spring AOP实现原理
SpringMVC的工作原理图: SpringMVC流程 . 用户发送请求至前端控制器DispatcherServlet. . DispatcherServlet收到请求调用HandlerMappin ...
- Hibernate 查询数据库中的数据
1.Criteria介绍 Criteria与Session绑定,其生命周期跟随着Session结束而结束,使用Criteria时进行查询时,每次都要于执行时期动态建立物件,并加入各种查询条件,随着Se ...
- 【编程技术-Shell】AWK使用大全
1. AWK中输出特殊字符 输出单引号 涉及到转义字符,但是在使用普通的方法进行转义时,会遇到下面的问题 正确的方法:'\'',使用单引号将转义字符括起来,然后后面加上单引号 输出其他特殊字符 输出 ...