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;
}