1 NuGet包安装npoi

2 安装npoi

3 获取txt文档内容,不需要安装npoi。filePath是相对路径
public static string ReadFileContent(string filePath)
{
string strFilePath = HttpContext.Current.Server.MapPath(filePath);
string strContent = "";
if (File.Exists(strFilePath))
{
//读取文本文件流
FileStream stream = new FileStream(strFilePath, FileMode.Open);
try
{
StreamReader reader = new StreamReader(stream, System.Text.Encoding.GetEncoding("utf-8"));
//定位到起始位置
reader.BaseStream.Position = 0;
//获取文本内容并替换特殊字符
strContent = reader.ReadToEnd().Replace(" ", " ").Replace("\r\n", "<br>");
//关闭文件流
stream.Close();
}
catch (Exception)
{
//关闭文件流
stream.Close();
}
}
return strContent;
}
4 获取.docx文件内容,必须NuGet动npoi安装后使用。注意:只能获取.docx
public static string ReadFileContentDoc(string filePath)
{
string strFilePath = HttpContext.Current.Server.MapPath(filePath);
string strContent = "";
if (File.Exists(strFilePath))
{
//读取文本文件流
FileStream stream = new FileStream(strFilePath, FileMode.Open);
try
{
//根据提供的文件,创建一个Word文档对象
XWPFDocument docx = new XWPFDocument(stream);
//获取Word文档的所有段落对象
IList<XWPFParagraph> paragraphs = docx.Paragraphs;
//……
foreach (var item in paragraphs)
{
strContent += item.ParagraphText + "<br>" + "  ";
}
//关闭文件流
stream.Close();
}
catch (Exception)
{
//关闭文件流
stream.Close();
}
}
return strContent;
}
NPOI与文本文件操作:.txt与.docx内容读取指南
本文介绍了如何使用NuGet包npoi处理不同格式文件,包括读取txt文件内容和解析.docx文档。通过实例展示了如何读取txt文件并替换特殊字符,以及在.npoi支持下获取.docx文件中的段落内容。
2502

被折叠的 条评论
为什么被折叠?



