软件编程
位置:首页>> 软件编程>> C#编程>> C#读取word中表格数据的方法实现

C#读取word中表格数据的方法实现

作者:ViperL1  发布时间:2023-09-12 22:54:53 

标签:C#,读取,word

前些日子有一个项目需要从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;    //关闭文件流(很关键,否则会导致下一个文件无法大开)

}

C#读取word中表格数据的方法实现

但是这样做又有一个缺点 ,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文件中的表格。

C#读取word中表格数据的方法实现

随后尝试了其getText()函数确定可以直接抓取文字内容,初步判断可能是格式问题。

C#读取word中表格数据的方法实现

有考虑过自己写匹配函数对文本内容进行分析,但由于格式过于复杂,很多通用性问题无法解决后放弃。如果格式不复杂的话,也不失为一种解决方法。

最后采用的方法是先利用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

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com