You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C#中通过Google Sheets API v4读取CellFormat并获取单元格的行高、文本颜色与字体样式?

嘿,我刚好做过类似的需求,这就给你一步步讲清楚怎么在C#里通过Google Sheets API v4读取CellFormat、行高、文本颜色和字体样式!

实现步骤与代码示例

1. 基础准备

首先确保你已经安装了Google Sheets API的官方NuGet包:

Install-Package Google.Apis.Sheets.v4

同时,你需要完成API认证——不管是用服务账号密钥(适合服务器端应用)还是OAuth2客户端凭据(适合桌面/移动端应用),确保你的凭据有SpreadsheetsReadonly权限。

2. 核心要点:必须显式请求格式字段

Google Sheets API默认只会返回单元格的原始值,格式信息(比如CellFormat、行高)需要你在请求时通过fields参数明确指定。这里我们要用Spreadsheets.Get接口,而不是只返回值的Values.Get。

3. 完整代码实现

下面是可直接参考的代码,我已经加了详细注释:

using Google.Apis.Auth.OAuth2;
using Google.Apis.Sheets.v4;
using Google.Apis.Sheets.v4.Data;
using Google.Apis.Services;
using System;

class SheetsFormatReader
{
    static void Main(string[] args)
    {
        // 替换成你的凭据路径和表格ID
        string credentialPath = "your-credentials-file.json";
        string spreadsheetId = "your-spreadsheet-id";
        string targetRange = "Sheet1!A1:C10"; // 指定要读取的单元格范围

        // 初始化Sheets服务
        var credential = GoogleCredential.FromFile(credentialPath)
            .CreateScoped(SheetsService.Scope.SpreadsheetsReadonly);

        var sheetsService = new SheetsService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = "Sheets Format Reader Demo"
        });

        // 创建获取表格数据的请求
        var getRequest = sheetsService.Spreadsheets.Get(spreadsheetId);
        getRequest.Range = targetRange;
        // 重点:指定要返回的字段,包含行元数据(行高)和单元格格式
        getRequest.Fields = "sheets(data(rowMetadata, startRow, endRow, values(userEnteredFormat, formattedValue)))";

        // 执行请求并获取响应
        var spreadsheetResponse = getRequest.Execute();

        // 解析响应数据
        foreach (var sheet in spreadsheetResponse.Sheets)
        {
            foreach (var sheetData in sheet.Data)
            {
                int currentRowIndex = sheetData.StartRow.Value;
                foreach (var rowData in sheetData.RowData)
                {
                    // 读取行高
                    if (rowData.RowMetadata != null)
                    {
                        Console.WriteLine($"行 {currentRowIndex + 1} 的行高: {rowData.RowMetadata.Height}px");
                    }

                    // 读取每个单元格的格式
                    if (rowData.Values != null)
                    {
                        foreach (var cellData in rowData.Values)
                        {
                            CellFormat cellFormat = cellData.UserEnteredFormat;
                            if (cellFormat != null)
                            {
                                // 读取文本颜色(RGB格式)
                                var textColor = cellFormat.TextFormat?.ForegroundColor;
                                if (textColor != null)
                                {
                                    Console.WriteLine($"文本颜色: R={textColor.Red:F2}, G={textColor.Green:F2}, B={textColor.Blue:F2}");
                                }

                                // 读取字体样式
                                var textFormat = cellFormat.TextFormat;
                                if (textFormat != null)
                                {
                                    Console.WriteLine($"字体信息: 字体={textFormat.FontFamily}, 字号={textFormat.FontSize}, 是否加粗={textFormat.Bold}");
                                }
                            }
                        }
                    }
                    currentRowIndex++;
                }
            }
        }
    }
}

4. 关键细节说明

  • fields参数的作用:这个参数是核心,它告诉API你需要哪些数据。我这里指定的字段包含:
    • rowMetadata:行的元数据,里面的Height就是行高
    • values(userEnteredFormat):每个单元格的用户设置格式,也就是你找到的CellFormat类
  • 空值检查:如果行高是默认值,或者单元格格式是默认样式,API不会返回对应的字段,所以一定要加null检查,避免空引用异常
  • CellFormat的属性:UserEnteredFormat里包含了所有格式设置,除了文本颜色和字体,你还能读取边框、背景色、对齐方式等其他格式

内容的提问来源于stack exchange,提问作者Vladimir Gulyaev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 08:52:41