我对编码和C#非常陌生。我正在构建一个通过API访问Google电子表格的应用,然后将这些数据转换为XML,将其压缩并写入流中。它可以正常工作,但是我不想再将每个电子表格ID手动添加到我的列表中,而是要进行另一个API调用,该API会检索我的Google Sheets帐户中的每个ID,以便我可以将它们存储到列表中,并在每次运行该应用程序时进行更新。
我要从墙上砸头寻找答案,但我认为这无法通过sheets API获得,但可能通过驱动器API可以实现??任何帮助将不胜感激,我不希望任何人寻求帮助编写代码,但是请指出正确的方向,还是我试图做一些无法完成的事情?
public class GoogleSheetsReader
{
private string apiKey;
public Stream OutStream { get; set; }
List<string> SpreadSheetIdList { get; set; }
public GoogleSheetsReader(string apiKey)
{
this.apiKey = apiKey;
}
public Stream Main()
{
SheetsService sheetsService = new SheetsService(new BaseClientService.Initializer
{
HttpClientInitializer = GetCredential(),
ApplicationName = "My Project To XML",
ApiKey = apiKey,
});
using (MemoryStream memory = new MemoryStream())
{
using (ZipArchive zip = new ZipArchive(memory, ZipArchiveMode.Create))
{
SpreadSheetIdList = new List<string>(); // not the best place for the list, just testing funtionality
SpreadSheetIdList.Add("1oZlfj6XZOrPs9Qti9K9iKL6itZChM8dlwwJFSvBNzUc");
SpreadSheetIdList.Add("1oU3sjd7QoOgQ2PvmC7NxciyM1MRXns6-Z9vMayFgOjU");
foreach (var spreadSheetId in SpreadSheetIdList)
{
var ssRequest = sheetsService.Spreadsheets.Get(spreadSheetId);
Data.Spreadsheet service = ssRequest.Execute();
foreach (var sheet in service.Sheets)
{
var sheetName = sheet.Properties.Title;
SpreadsheetsResource.ValuesResource.GetRequest request = sheetsService.Spreadsheets.Values.Get(spreadSheetId, sheetName);
SpreadsheetsResource.GetRequest requestForSpreadSheet = sheetsService.Spreadsheets.Get(spreadSheetId);
requestForSpreadSheet.Ranges = sheetName;
Data.Spreadsheet response1 = requestForSpreadSheet.Execute();
var spreadSheetName = response1.Properties.Title;
Data.ValueRange response = request.Execute();
ZipArchiveEntry entry = zip.CreateEntry($"{spreadSheetName}\\{sheetName}.xml");
using (Stream ZipFile = entry.Open())
{
byte[] data = Encoding.ASCII.GetBytes(SchemaMaker(response)); // SchemaMaker converts my sheet data to required xml format
ZipFile.Write(data, 0, data.Length);
}
}
}
}
OutStream = new MemoryStream(memory.ToArray());
}
return OutStream;
}
public string SchemaMaker(ValueRange _param)
{
var result = "<TABLE>";
var headers = _param.Values[0];
for (int i = 1; i < _param.Values.Count; i++)
{
result = result + "<ROW>";
for (int j = 0; j < _param.Values[i].Count; j++)
{
result = result + $"<{headers[j]}>{_param.Values[i][j]}</{headers[j]}>";
}
result = result + "</ROW>";
}
result = result + "</TABLE>";
var element = XElement.Parse(result);
var settings = new System.Xml.XmlWriterSettings();
settings.OmitXmlDeclaration = true;
settings.Indent = true;
settings.NewLineOnAttributes = true;
var xmlFormat = element.ToString();
return xmlFormat;
}
public static UserCredential GetCredential()
{
string[] Scopes = { SheetsService.Scope.SpreadsheetsReadonly };
return null;
}
}