在C#中操作Word文档时,如何处理表格中的数据?

在 C# 中操作 Word 表格数据时,需结合使用的库(如Microsoft.Office.Interop.WordDocX)进行数据填充、读取、修改、验证等操作。以下分场景详细说明处理方法:

一、数据填充(写入表格)

1. 使用 Interop.Word 填充数据

csharp
 
运行
// 假设已创建表格table(3行4列)
// 方式1:按单元格索引填充
table.Cell(2, 1).Range.Text = "张三"; // 第2行第1列
table.Cell(2, 2).Range.Text = "28";

// 方式2:遍历行/列批量填充
string[,] data = { 
    { "李四", "32", "市场部", "2022-05-20" },
    { "王五", "25", "财务部", "2024-03-10" }
};

for (int i = 0; i < data.GetLength(0); i++)
{
    int rowIndex = i + 2; // 从第2行开始(表头为第1行)
    for (int j = 0; j < data.GetLength(1); j++)
    {
        table.Cell(rowIndex, j + 1).Range.Text = data[i, j];
    }
}
 

2. 使用 DocX 填充数据

csharp
 
运行
Table table = document.AddTable(3, 4);
// 直接赋值单元格文本
table.Rows[1].Cells[0].Paragraphs.First().Append("张三");
table.Rows[1].Cells[1].SetText("28"); // 简化写法

// 批量填充
var dataList = new List<string[]>
{
    new[] { "李四", "32", "市场部", "2022-05-20" },
    new[] { "王五", "25", "财务部", "2024-03-10" }
};

for (int i = 0; i < dataList.Count; i++)
{
    for (int j = 0; j < dataList[i].Length; j++)
    {
        table.Rows[i + 1].Cells[j].Paragraphs.First().Append(dataList[i][j]);
    }
}
 

二、数据读取(从表格提取内容)

1. 使用 Interop.Word 读取数据

csharp
 
运行
// 读取单个单元格
string name = table.Cell(2, 1).Range.Text.Trim(); // 去除多余符号

// 遍历读取所有数据
List<Dictionary<string, string>> tableData = new List<Dictionary<string, string>>();
string[] headers = { "姓名", "年龄", "部门", "入职日期" };

for (int row = 2; row <= table.Rows.Count; row++) // 跳过表头
{
    Dictionary<string, string> rowData = new Dictionary<string, string>();
    for (int col = 1; col <= table.Columns.Count; col++)
    {
        string cellText = table.Cell(row, col).Range.Text.Trim('\r', '\a'); // 清理Word特殊字符
        rowData.Add(headers[col - 1], cellText);
    }
    tableData.Add(rowData);
}

// 输出读取结果
foreach (var row in tableData)
{
    Console.WriteLine($"姓名:{row["姓名"]},部门:{row["部门"]}");
}
 

2. 使用 DocX 读取数据

csharp
 
运行
List<string[]> data = new List<string[]>();
foreach (TableRow row in table.Rows.Skip(1)) // 跳过表头
{
    string[] rowData = new string[row.Cells.Count];
    for (int i = 0; i < row.Cells.Count; i++)
    {
        rowData[i] = row.Cells[i].Paragraphs.First().Text;
    }
    data.Add(rowData);
}
 

三、数据修改(更新表格内容)

1. 修改单元格值

csharp
 
运行
// Interop.Word
table.Cell(2, 2).Range.Text = "29"; // 直接覆盖文本

// DocX
table.Rows[1].Cells[1].Paragraphs.First().ReplaceText("28", "29"); // 替换原有内容
 

2. 动态添加行 / 列并填充数据

csharp
 
运行
// Interop.Word:添加新行
table.Rows.Add();
int newRow = table.Rows.Count;
table.Cell(newRow, 1).Range.Text = "赵六";
table.Cell(newRow, 2).Range.Text = "30";

// DocX:插入新行
TableRow newRow = table.InsertRow(table.Rows.Count);
newRow.Cells[0].Paragraphs.First().Append("赵六");
 

四、数据验证与格式化

1. 数据类型验证

csharp
 
运行
 
// 验证年龄是否为数字
string ageText = table.Cell(2, 2).Range.Text.Trim();
if (!int.TryParse(ageText, out int age))
{
    // 标记错误单元格
    table.Cell(2, 2).Range.Shading.BackgroundPatternColor = WdColor.wdColorRed;
    throw new Exception("年龄格式错误!");
}
 

2. 格式化日期 / 数字

csharp
 
运行
// Interop.Word:格式化日期单元格
string dateText = "2023-01-15";
if (DateTime.TryParse(dateText, out DateTime date))
{
    table.Cell(2, 4).Range.Text = date.ToString("yyyy年MM月dd日");
    table.Cell(2, 4).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
}
 

五、批量操作与性能优化

  1. 禁用 Word 界面更新(Interop):
    csharp
     
    运行
     
     
    wordApp.ScreenUpdating = false; // 批量操作前禁用,提升速度
    // 执行数据填充/修改...
    wordApp.ScreenUpdating = true;
     
  2. 使用数组缓存数据:避免频繁访问 Word 对象模型,先将数据存入数组,再一次性写入表格。

六、常见问题处理

  1. 特殊字符清理:Word 单元格文本可能包含\r\a等符号,需用Trim('\r', '\a')清理。
  2. 跨行 / 跨列单元格:通过table.Cell(row, col).MergeCells()合并,读取时需判断合并范围。
  3. 空值处理:填充前检查数据是否为null,避免写入空字符串导致格式异常。

总结

处理 Word 表格数据的核心是按行列索引定位单元格,结合库的 API 进行读写操作。Interop.Word 功能更全但需处理 COM 对象释放,DocX 更轻量且易用。根据场景选择合适的库,并注意批量操作时的性能优化和数据验证,可高效处理表格数据。
posted @ 2025-11-26 20:23  福寿螺888  阅读(0)  评论(0)    收藏  举报