简体   繁体   中英

How do I clear all formatting for a specified sheet within a Google Spreadsheet using C#?

My application is currently able to transfer all of the values from a specified sheet within an Excel Spreadsheet to a Google Sheet, and clear all values from a specified sheet within a Google Sheet using the ClearValuesRequest .

How can I clear all formatting (font styles, cell colors, etc) from a specified sheet within a Google Spreadsheet? I have spent hours looking through the documentation but am failing to understand exactly what I need to do as it doesn't seem as straight forward as using the ClearValuesRequest .

This code works as far as clearing just the values from a spreadsheet.

        public string ClearSheetData(string spreadsheetId, string sheetName)
        {
            try
            {
                GoogleConnections googleConnections = new GoogleConnections();
                new ConnectToGoogle().ConnectToGoogleSheets(googleConnections, ClientSecretFilePath, ApplicationName, UserName);

                sheetName = sheetName.Replace("!", "").Replace("$","");
                sheetName = string.Concat(sheetName, "!").TrimEnd();

                string range = string.Concat(sheetName, "A:ZZ");

                ClearValuesRequest requestBody = new ClearValuesRequest();

                SpreadsheetsResource.ValuesResource.ClearRequest clearRequest =
                    googleConnections.sheetsService.Spreadsheets.Values.Clear(requestBody, spreadsheetId, range);

                clearRequest.Fields = "*";  //I had hoped that this would clear the formats as well.  But it seems to be used as a selector for a partial response.

                ClearValuesResponse response = clearRequest.Execute();

                return (JsonConvert.SerializeObject(response));

            }
            catch (Exception e)
            {
                return string.Concat("Message: ", e.Message, Environment.NewLine, "StackTrace:  ", e.StackTrace, Environment.NewLine, "InnerException:  ", e.InnerException);
            }
        }

To answer my own question this is what worked for me. If there was/is a better way then I am unaware of it.

After much research I could not find an option to Clear any formatting using the ClearValuesRequest . I had to perform a BatchUpdateSpreadsheetRequest instead. From there I had to use a RepeatCellRequest and supply a GridRange for the Range to repeat the cell in. Unfortunately the GridRange doesn't accept A1 notation, therefore I had to create Helper methods to convert the range in A1 notation to indexes.

This clears/resets all of the formatting for the entire sheet.

ClearFormatting Method

public string ClearFormatting(SheetsService sheetsService, string spreadsheetId, string sheetName, string range)
        {
            string str = string.Empty;
            try
            {
                GoogleSheetsHelper helper = new GoogleSheetsHelper();
                range = helper.RemoveSheetNameHelper(range);
                string[] strArray = range.Split(':');
                List<Request> requestList = new List<Request>();
                BatchUpdateSpreadsheetRequest body = new BatchUpdateSpreadsheetRequest()
                {
                    Requests = (IList<Request>)requestList
                };
                int sheetId = helper.GetSheetIdHelper(sheetsService, spreadsheetId, sheetName);

                Request request = new Request()
                {
                    RepeatCell = new RepeatCellRequest()
                    {
                        Range = new GridRange()
                        {
                            SheetId = new int?(sheetId),
                            StartColumnIndex = new int?(GoogleSheetsHelper.A1ToColumnHelper(strArray[0]) - 1),
                            StartRowIndex = new int?(GoogleSheetsHelper.A1ToRowHelper(strArray[0]) - 1),
                        },
                     Fields = "*"
                    }
                };
                body.Requests.Add(request);
                BatchUpdateSpreadsheetResponse response = sheetsService.Spreadsheets.BatchUpdate(body, spreadsheetId).Execute();
                str = JsonConvert.SerializeObject(response);

            }
            catch (Exception e)
            {
                str = "Message" + e.Message + Environment.NewLine + Environment.NewLine + "InnerException:  " + e.InnerException + Environment.NewLine + Environment.NewLine + "Data:  " + e.Data + Environment.NewLine + Environment.NewLine + "HelpLink:  " + e.HelpLink + Environment.NewLine + Environment.NewLine + "Source:  " + e.Source + Environment.NewLine + Environment.NewLine + "StackTrace:  " + e.StackTrace + Environment.NewLine + Environment.NewLine + "TargetSite:  " + e.TargetSite + Environment.NewLine + Environment.NewLine;
            }
            return str;
        }

A1ToRowHelper

internal static int A1ToRowHelper(string a1)
        {
            string empty = string.Empty;
            string str = a1;
            for (int i = 0; i < str.Length; i++)
            {
                char chr = str[i];
                if (char.IsNumber(chr))
                {
                    empty = string.Concat(empty, chr.ToString());
                }
            }
            return int.Parse(empty);
        }

A1ToColumnHelper

internal static int A1ToColumnHelper(string a1)
        {
            string empty = string.Empty;
            string str = a1;
            for (int i = 0; i < str.Length; i++)
            {
                char chr = str[i];
                if (char.IsLetter(chr))
                {
                    empty = string.Concat(empty, chr.ToString());
                }
            }
            if (string.IsNullOrEmpty(a1))
            {
                throw new ArgumentNullException("a1");
            }
            empty = empty.ToUpperInvariant();
            int num = 0;
            for (int i = 0; i < empty.Length; i++)
            {
                char chr1 = empty[i];
                num *= 26;
                num = num + chr1 - 65 + 1;
            }
            return num;
        }

GetSheetIdHelper

public int GetSheetIdHelper(SheetsService sheetsService, string spreadsheetId, string sheetName)
        {
            Sheet sheet = sheetsService.Spreadsheets.Get(spreadsheetId).Execute().Sheets.First<Sheet>((Sheet x) => x.Properties.Title.Equals(sheetName));
            int? sheetId = sheet.Properties.SheetId;
            return (sheetId.HasValue ? sheetId.GetValueOrDefault() : 0);
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM