I am working with Google Sheet API. I am facing problem to read cell Note.
As below image, I am able to reading cell value i.e. "Ajay Gangwar", but not able to read cell note i.e. "Senior Software Engineer".
Below code working fine to read data from Google Sheet:
private static void readGoogleSheetNote(SheetsService sheetsService)
{
string spreadsheetId = "1FvPaJVu5z_Vml8eIqPK7q2WOWosOH-llL4p3FItg6Zo";
string range = "Sheet1";
SpreadsheetsResource.ValuesResource.GetRequest.ValueRenderOptionEnum valueRenderOption = (SpreadsheetsResource.ValuesResource.GetRequest.ValueRenderOptionEnum)0;
SpreadsheetsResource.ValuesResource.GetRequest.DateTimeRenderOptionEnum dateTimeRenderOption = (SpreadsheetsResource.ValuesResource.GetRequest.DateTimeRenderOptionEnum)0;
SpreadsheetsResource.ValuesResource.GetRequest getRequest = sheetsService.Spreadsheets.Values.Get(spreadsheetId, range);
getRequest.ValueRenderOption = valueRenderOption;
getRequest.DateTimeRenderOption = dateTimeRenderOption;
Google.Apis.Sheets.v4.Data.ValueRange response = getRequest.Execute();
Console.WriteLine(JsonConvert.SerializeObject(response));
Console.ReadKey();
}
The output of the above code is:
You have to use the Method: spreadsheets.get to get the cell notes, as seen on the Overview of Cells from this resource.
Using the following script you will get the data from the A4 cell. Inside the response there is the notes field:
String spreadsheetId = "SPREADSHEET ID";
String range = "Sheet1!A4";
bool includeGridData = true;
SpreadsheetsResource.GetRequest request = service.Spreadsheets.Get(spreadsheetId);
request.Ranges = range;
request.IncludeGridData = includeGridData;
Data.Spreadsheet response = request.Execute();
Console.WriteLine(JsonConvert.SerializeObject(response.Sheets));
Related
Okay, so i have an excel file (.xlsx) which will be downloaded when user clicks a button. The file is stored in a folder and will be processed by adding data validation and such before sending it to user. In my case i'm only adding dropdowns which will be filled from another sheet.
Here is my code that generates the file:
public IActionResult DownloadTemplateExcelFile(string type)
{
string fullFilePath = "../TemplateFiles/";
string fileName = "";
if (type != "")
{
fileName = type + ".xlsx";
fullFilePath += fileName;
}
var fileData = ExcelHelper.CreateExcelFile(type, fullFilePath);
return this.File(fileData, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",fileName);
}
And this code below is the file processing:
public static class ExcelHelper{
public static byte[] CreateExcelFile(string type, string fullFilePath){
using (var package = new ExcelPackage(new FileInfo(fullFilePath))){
// Getting list of values and set it for dropdown values
// List<string> dropdown1 = .. list string is loaded from database
ExcelWorksheet sheetDropdown1 = package.Workbook.Worksheets.Add("Dropdowns1");
var mainSheet= package.Workbook.Worksheets["Sheet1"];
sheetDropdown1.Cells["A1"].LoadFromCollection(dropdown1);
var dropdown1Addr = mainSheet.Cells[3,5,300,5].Address;
var dropdown1Formula = "='Dropdowns1'!$A:$A";
var validation = mainSheet.DataValidations.AddListValidation(dropdown1Addr);
validation.ShowErrorMessage = true;
validation.ErrorStyle = OfficeOpenXml.DataValidation.ExcelDataValidationWarningStyle.stop;
validation.ErrorTitle = "An invalid value was entered";
validation.Error = "Select a value from the list";
validation.AllowBlank = true;
validation.Formula.ExcelFormula = dropdown1Formula;
validation.Validate();
var excelFile = package.GetAsByteArray();
package.Dispose();
return excelFile;
}
}
}
When i opened the file in Excel 2010+ it worked just fine, the dropdown is loaded nicely and the cells in which the data validation is applied is working. However in excel 2007 when i tried to open it showed an error need to repair if i want to open it in 2007. If i do so however, the dropdown function is lost and unusable.
I've racked my brain but still haven't found any solution yet. How can i "Fix" this? I'm using EPPlus 6 for reference.
I have a document that I need to update on a monthly basis and I'm writing an automation to do so. This is my first time attempting to update a document with C# as opposed to simply creating a new one. I have researched and tried implementing a few libraries that I've found online and here on StackOverflow, for example, ClosedXML, but so far I've had no luck. I understand this question has been asked here before, so my actual question is: Is my implementation incorrect/am I doing something wrong?
public void WriteToReport(List<BrandData> brandData, string reportFilePath)
{
using (var workbook = new XLWorkbook(reportFilePath))
{
var worksheet = workbook(1);
worksheet.Cell(26, 2).Value = "Hello World!";
workbook.SaveAs(reportFilePath);
}
}
Above is how I've tried to test ClosedXML so far. The GitHub docs imply that it should be this simple, but I don't see any changes made to the doc when the automation is finished. I've also tried using Streamwriter. If anyone can help me with ClosedXML or suggest another library that worked for them, it would be greatly appreciated.
Edit: Following explanations on other similar questions on here, I have tried this:
public void WriteToReport(List<BrandData> brandData, string reportFilePath)
{
var workbook = new XLWorkbook(reportFilePath);
var worksheet = workbook.Worksheet(1);
int numberOfLastColumn =
worksheet.LastColumnUsed().ColumnNumber();
IXLCell newCell = worksheet.Cell(numberOfLastColumn + 1, 1);
newCell.SetValue("Hello World");
workbook.SaveAs(reportFilePath);
}
Here is a simple example to write a string value to the first WorkSheet.
public void WriteToCell(string fileName, int row, int col, string value)
{
using var workbook = new XLWorkbook(fileName);
var worksheet = workbook.Worksheets.Worksheet(1);
worksheet.Cell(row, col).Value = value;
workbook.SaveAs(fileName);
}
This question is related to Google Sheets API (C#).
I have to write more than 1000 rows into a Google sheet, therefore I need to increase the number of rows (I got the Google.Apis.Requests.RequestError when I attempted to write 4640 rows).
Searching the Stack Overflow website resulted in information telling me that I needed to use UpdateSheetPropertiesRequest or InsertDimensionRequest and create a new request that could be in the same Spreadsheets.BatchUpdate call.
In line with this Python example, I set the properties of the InsertDimensionRequest instance and included them in my existing code (= publicly available C# code by Ian Preston).
The code then looks like this:
public void AddCells(GoogleSheetParameters googleSheetParameters, List<GoogleSheetRow> rows)
{
var requests = new BatchUpdateSpreadsheetRequest { Requests = new List<Request>() }; //Existing code
int sheetId = GetSheetId(_sheetsService, _spreadsheetId, googleSheetParameters.SheetName); //Existing code
InsertDimensionRequest insertDimensionRequest = new InsertDimensionRequest(); //Added code
insertDimensionRequest.Range.SheetId = sheetId; //Added code
insertDimensionRequest.Range.Dimension = "ROWS"; //Added code
insertDimensionRequest.Range.StartIndex = 999; //Added code
insertDimensionRequest.Range.EndIndex = 6999; //Added code
insertDimensionRequest.InheritFromBefore = false; //Added code
var request = new Request { UpdateCells = new UpdateCellsRequest { Start = gc, Fields = "*" } }; //Existing code
//some code here
var request1 = new Request { ???????? }; //code to be added - how should the request look like?
requests.Requests.Add(request); //Existing code
requests.Requests.Add(request1); //Added code
}
But I do not know how a new request can be created in C#.
My question is: How to create such an request (named as request1 in my code)?
Meanwhile, I have managed to figure out an answer.
DimensionRange dr = new DimensionRange
{
SheetId = sheetId,
Dimension = "ROWS",
StartIndex = 999,
EndIndex = 6999 // adding extra 6000 rows
};
var request1 = new Request { InsertDimension = new InsertDimensionRequest { Range = dr, InheritFromBefore = false } };
And then (the order of the requests matters):
requests.Requests.Add(request1);
requests.Requests.Add(request);
EDIT 01-06-2022: The entire code using the aforementioned snippet can be downloaded from GitHub - see the GoogleSheets project there.
It is also possible to use userEnteredValue. This clears the sheet and, for me inexplicably, sets the number of rows to an unknow value, but my 4640 rows were accepted.
EDIT 31-05-2022: If you know more about the usage of userEnteredValue, feel free to elaborate on this matter.
GridRange dr2 = new GridRange
{
SheetId = sheetId
};
var request2 = new Request { UpdateCells = new UpdateCellsRequest { Range = dr2, Fields = "userEnteredValue" } };
And then (the order of the requests probably also matters):
requests.Requests.Add(request2);
requests.Requests.Add(request);
oFax = mRightFaxComServer.Faxes[faxFileInfo.RightFaxSettings.RightFaxServerObject].Create;
oFax.OwnerID = faxFileInfo.RightFaxSettings.OwnerId;
oFax.ToName = recipientDetails.RecipientName;
oFax.ToFaxNumber = recipientDetails.FaxNumber;
oFax.FromName = recipientDetails.SenderName;
oFax.Attachments.Add(fileName);
oFax.NeedsPDFConversion = true;
oFax.isFineMode = true;
oFax.NeedsPreScan = true;
oFax.CoverSheetNotes[1] = recipientDetails.Notes;
These lines added to send cover sheet notes but we are not able to see notes population on cover sheet.
Above code works for version 9.6 as expected
I have a server that returns large amounts of comma separated data in an http response. I need to import this data into excel.
I have this working by passing the contents to a temp file and then reading the temp file as a csv, but this process seems inefficient. The query tables can read directly from the http response, but it puts each line of data into a single cell, rather than separating into one cell per comma.
Is it possible to read comma separated data from an http response directly into excel from a C# excel add-in?
Thanks!
public static void URLtoCSV(string URL, Excel.Worksheet destinationSheet, Excel.Range destinationRange, int[] columnDataTypes, bool autoFitColumns)
{
destinationSheet.QueryTables.Add(
"URL;" + URL,
destinationRange, Type.Missing);
destinationSheet.QueryTables[1].Name = URL;
destinationSheet.QueryTables[1].FieldNames = true;
destinationSheet.QueryTables[1].RowNumbers = false;
destinationSheet.QueryTables[1].FillAdjacentFormulas = false;
destinationSheet.QueryTables[1].PreserveFormatting = true;
destinationSheet.QueryTables[1].RefreshOnFileOpen = false;
destinationSheet.QueryTables[1].RefreshStyle = XlCellInsertionMode.xlInsertDeleteCells;
destinationSheet.QueryTables[1].SavePassword = false;
destinationSheet.QueryTables[1].SaveData = true;
destinationSheet.QueryTables[1].AdjustColumnWidth = true;
destinationSheet.QueryTables[1].RefreshPeriod = 0;
destinationSheet.QueryTables[1].Refresh(false);
if (autoFitColumns == true)
destinationSheet.QueryTables[1].Destination.EntireColumn.AutoFit();
}
The easier solution than the one you reference is to use the type of "TEXT" instead of URL. TEXT supports all CSV imports, including from HTTP sources. URL appears to be designed to handle screen scraping more than anything else.
e.g. in your case:
destinationSheet.QueryTables.Add("URL;" + URL,
becomes
destinationSheet.QueryTables.Add("TEXT;" + URL,
And for those stumbling upon this post asking the same question but with VB scripting in Excel, the complete solution would look like:
' Load new data from web
With ActiveSheet.QueryTables.Add(Connection:="TEXT;http://yourdomain.com/csv.php", Destination:=Range("$A$1"))
.TextFileCommaDelimiter = True
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlOverwriteCells
.SavePassword = False
.SaveData = False
.AdjustColumnWidth = True
.Refresh BackgroundQuery:=False
End With