【C# 获取Word文档中的表格数据】

发现有些电脑中使用NPOI读取word文档会出现 Wrong Local header signature: 0xE011CFD0 的报错
于是就使用Spire.Doc 来获取word文档中的表格数据
代码如下

		private string[][] GetDocX2(int index, string Path)
        {
            Spire.Doc.Document doc = new Spire.Doc.Document();
            doc.LoadFromFile(Path);
            Spire.Doc.Table table = doc.Sections[0].Tables[index] as Table;
            string[][] tableData = new string[table.Rows.Count][];
            //遍历表格内容
            for (int i = 0; i < table.Rows.Count; i++)
            {
                var cellsindex = table.Rows[i].Cells.Count;
                tableData[i] = new string[cellsindex];
                for (int j = 0; j < cellsindex; j++)
                {
                    TableCell cell = table.Rows[i].Cells[j];
                    string txt = "";
                    foreach (Paragraph paragraph in cell.Paragraphs)
                    {
                        txt += paragraph.Text;
                    }
                    tableData[i][j] = txt;
                }
            }
            return tableData;
        }

index 是word文档中的表格下标数,可以使用doc.Sections[0].Tables.Count 来获取文档中的表格数量

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C#处理Word文档表格,可以使用Microsoft.Office.Interop.Word命名空间提供的API进行操作。以下是一个示例代码,可以在Word文档的指定位置创建一个表格,并设置表格的行列数、表头和内容: ```csharp using System; using Microsoft.Office.Interop.Word; namespace WordTableDemo { class Program { static void Main(string[] args) { // 创建Word文档对象 Application wordApp = new Application(); Document wordDoc = wordApp.Documents.Add(); // 在指定位置插入表格 Range range = wordDoc.Range(0, 0); Table table = wordDoc.Tables.Add(range, 4, 3); // 设置表头 table.Cell(1, 1).Range.Text = "姓名"; table.Cell(1, 2).Range.Text = "年龄"; table.Cell(1, 3).Range.Text = "性别"; // 设置表格内容 table.Cell(2, 1).Range.Text = "张三"; table.Cell(2, 2).Range.Text = "18"; table.Cell(2, 3).Range.Text = "男"; table.Cell(3, 1).Range.Text = "李四"; table.Cell(3, 2).Range.Text = "20"; table.Cell(3, 3).Range.Text = "女"; table.Cell(4, 1).Range.Text = "王五"; table.Cell(4, 2).Range.Text = "22"; table.Cell(4, 3).Range.Text = "男"; // 保存Word文档 wordDoc.SaveAs2(@"D:\test.docx"); wordDoc.Close(); // 关闭Word应用程序 wordApp.Quit(); } } } ``` 在上述代码,我们首先创建了一个Word文档对象,然后通过`Range`对象在指定位置插入了一个4行3列的表格。接着,我们通过`table.Cell(row, column)`方法获取表格某个单元格,并设置了表头和表格内容。最后,我们将Word文档保存到本地,并关闭Word应用程序。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值