日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

C#讀取word中表格數據的方法實現_C#教程

作者:ViperL1 ? 更新時間: 2022-08-06 編程語言

前些日子有一個項目需要從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

欄目分類
最近更新