網站首頁 編程語言 正文
前些日子有一個項目需要從word文件中取表格數據并進行處理,網上大部分方案都是基于office的com組件實現,但是這樣有一個缺點,如果電腦里沒有安裝office將無法使用,因為之前操作excel都是使用的NPOI,所以理所當然的想用NPOI解決此問題。
于是找到了如下代碼
private List<string> GetDoc(string Path)
{
if (Path == "")
return null; //文件路徑為空
List<string> Result = new List<string>(); //結果容器
FileStream stream = new FileStream(Path, FileMode.Open); //打開流
XWPFDocument docx = new XWPFDocument(stream);
var list = new List<XWPFTableCell>();
//循環遍歷表格內容
foreach (var row in docx.Tables[0].Rows)
{
foreach (var cell in row.GetTableCells())
{
if (!list.Contains(cell))
{
list.Add(cell);
Result.Add(cell.GetText());
}
}
}
stream.Close();
return Result; //關閉文件流(很關鍵,否則會導致下一個文件無法大開)
}
但是這樣做又有一個缺點 ,NPOI僅支持.docx格式的文件,如果讀取.doc會直接報錯!
于是后續又找到了另一開源組件freeSpire。有如下代碼
private List<string> GetDocX(string Path)
{
if (Path == "")
return null; //文件路徑為空
List<string> Result = new List<string>();
Spire.Doc.Document doc = new Spire.Doc.Document();
doc.LoadFromFile(Path);
TextBox textbox = doc.TextBoxes[0];
Spire.Doc.Table table = textbox.Body.Tables[0] as Spire.Doc.Table;
foreach (TableRow row in table.Rows)
{
foreach (TableCell cell in row.Cells)
{
foreach (Paragraph paragraph in cell.Paragraphs)
{
Result.Add(paragraph.Text);
}
}
}
return Result;
}
但是不知道什么原因,并不能抓取.doc文件中的表格。
隨后嘗試了其getText()函數確定可以直接抓取文字內容,初步判斷可能是格式問題。
有考慮過自己寫匹配函數對文本內容進行分析,但由于格式過于復雜,很多通用性問題無法解決后放棄。如果格式不復雜的話,也不失為一種解決方法。
最后采用的方法是先利用Spire組件將.doc轉換為.docx后再利用NPOI進行內容處理,效果拔群!!!
private string ChangeToDocx(string Path)
{
if (Path == "")
return ""; //文件路徑為空
List<string> Result = new List<string>();
Spire.Doc.Document doc = new Spire.Doc.Document();
doc.LoadFromFile(Path); //打開文件
Path.Replace(".doc", "docx"); //替換后綴
doc.SaveToFile(Path, FileFormat.Docx); //保存為.doc
return Path;
}
主函數中調用如下:(若不是.doc則無需轉換以節約開銷)
if (Path.Contains(".doc"))
{
string newPath = ChangeToDocx(Path);
result = GetDoc(newPath);
}
result = GetDoc(Path);
原文鏈接:https://blog.csdn.net/weixin_37878740/article/details/125230980
相關推薦
- 2022-10-17 漫談C++哈夫曼樹的原理及實現_C 語言
- 2022-09-14 python單鏈路性能測試實踐_python
- 2022-03-12 Nginx熱部署的實現_nginx
- 2022-05-04 python設計模式之單例模式你了解多少_python
- 2022-07-26 ubuntu18.04+cuda10.2+tensorrt8.4.1.5配置安裝
- 2023-12-14 Excel中——日期列后添加星期
- 2022-12-05 Linux中的grep?-v、-e、-E用法小結_linux shell
- 2022-05-05 docker中通過nginx+confd動態生成配置的解決方案_docker
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支