EPPlus - How to remove a comment from a cell? - epplus

In EPPlus I can add comments to cell in a worksheet using workSheet.Cells[x, y].AddComment()
But how do I remove a comment from a given cell - there isn't a workSheet.Cells[i, j].RemoveComment() - I need to leave any other comments in place
Thanks in advance for any suggestions

One would think it would be that simple :).
Check this out:
[TestMethod]
public void Comment_Test()
{
var existingFile = new FileInfo(#"c:\temp\temp.xlsx");
if (existingFile.Exists)
existingFile.Delete();
using (var package2 = new ExcelPackage(existingFile))
{
var ws = package2.Workbook.Worksheets.Add("Sheet1");
ws.Cells[1, 1].AddComment("Comment Test 1", "Me");
ws.Cells[1, 2].AddComment("Comment Test 2", "Me");
ws.Cells[1, 3].AddComment("Comment Test 3", "Me");
//Alternate way to add a comment
ws.Comments.Add(ws.Cells[1, 4], "Comment Test 4", "Me");
//Remove middle comment
ws.Comments.Remove(ws.Cells[1,2].Comment);
package2.Save();
}
}

Related

GOOGLE DOCS API Invalid requests[0].updateTextStyle: Index 4 must be less than the end index of the referenced segment, 2.",

I've created a document using Google Docs API, but when I try to modify its options or add text, it gives me this error:
http://prntscr.com/naf0nm
The thing is if I open the document and click enter many times ( to make many lines) then execution and modification works. Can anyone help me?? What do I need to do to not get this error?
String text1 = "hola, llegó papa";
List<Request> requests = new ArrayList<>();
requests.add(new Request().setInsertText(new InsertTextRequest()
.setText(text1)
.setLocation(new Location().setIndex(25))));
BatchUpdateDocumentRequest body = new BatchUpdateDocumentRequest().setRequests(requests);
BatchUpdateDocumentResponse response = service.documents()
.batchUpdate(idDoc, body).execute();
Here the method to create doc:
private static void createDoc(Docs service) throws IOException {
Document doc = new Document()
.setTitle("TEXTO CAMBIADO");
doc = service.documents().create(doc)
.execute();
System.out.println("Created document with title: " + doc.getTitle());
idDoc = doc.getDocumentId();
}
It is very late for answer but it can help to others.
May be this answer can help you. someone has answered here
Also you have to write backword to get the last inserted text at the starting of doc.
I just found another way to write text at end of doc. You don't need to set the location, just do this way..
public void insertText(Docs docsService) throws IOException {
List<Request> requests = new ArrayList<>();
requests.add(new Request().setInsertText(new InsertTextRequest()
.setText("Name : {{NAME}}\n")
.setEndOfSegmentLocation(new EndOfSegmentLocation())));
requests.add(new Request().setInsertText(new InsertTextRequest()
.setText("\nDOB: {{DOB}}\n")
.setEndOfSegmentLocation(new EndOfSegmentLocation())));
requests.add(new Request().setInsertText(new InsertTextRequest()
.setText("\nMobile: {{MOBILE}}\n")
.setEndOfSegmentLocation(new EndOfSegmentLocation())));
BatchUpdateDocumentRequest body = new BatchUpdateDocumentRequest().setRequests(requests);
BatchUpdateDocumentResponse response = docsService.documents()
.batchUpdate(Constants.DOCUMENT_ID, body).execute();
}

Discord .NET Value of type EmbedBuilder cannot be converted to Embed

As the title says i get "Value of type EmbedBuilder cannot be converted to Embed" error.
This is the code i'm trying right now :
If msg.Equals("gDurum") Then
Dim eb As New EmbedBuilder With {
.Title = "Sunucu Bilgisi",
.Color = New Color(255, 0, 0),
.ImageUrl = "https://cache.gametracker.com/server_info/185.198.73.27:27015/b_560_95_1.png",
.Description = "Deneme"
}
eb.Build()
Await message.Channel.SendMessageAsync("", False, eb)
OK. I found the solution. I was trying to pass the EmbedBuilder instead of Embed.
Here's my new code :
If msg.Equals("gDurum") Then
Dim eb As New EmbedBuilder With {
.Title = "Sunucu Bilgisi",
.Color = New Color(255, 0, 0),
.ImageUrl = "https://cache.gametracker.com/server_info/185.198.73.27:27015/b_560_95_1.png",
.Description = "Deneme"
}
Await message.Channel.SendMessageAsync("", False, eb.Build())
For those who are looking at the official code example might encounter type mismatch while compiling.
Make sure to build Discord.Embed into a Rich Embed which is ready to be sent.
Corrected & working code example for this:
[Command("embed")]
public async Task SendRichEmbedAsync()
{
var embed = new EmbedBuilder
{
// Embed property can be set within object initializer
Title = "Hello world!"
Description = "I am a description set by initializer."
};
// Or with methods
embed.AddField("Field title",
"Field value. I also support [hyperlink markdown](https://example.com)!")
.WithAuthor(Context.Client.CurrentUser)
.WithFooter(footer => footer.Text = "I am a footer.")
.WithColor(Color.Blue)
.WithTitle("I overwrote \"Hello world!\"")
.WithDescription("I am a description.")
.WithUrl("https://example.com")
.WithCurrentTimestamp();
await ReplyAsync(embed: embed.Build());
}

Google Sheets API addProtectedRange Error: No grid with id: 0

I am not sure if I am making a mistake or if possibly this is related to the same issue reported here:
Google Sheets API V4 - Autofill Error - No grid with id: 0
I am getting:
HttpError 400
"Invalid requests[0].addProtectedRange: No grid with id: 1"
Code is something like this (additional addProtectedRange objects removed)
def add_protected_ranges(spreadsheet_id):
service = get_sheets_service()
requests = [
{
"addProtectedRange": {
'protectedRange': {
"range": {
"sheetId": 1,
"startRowIndex": 0,
"endRowIndex": 0,
"startColumnIndex": 0
},
"description": "Headers must not be changed",
"warningOnly": True
}
}
}
]
body = {
'requests': requests
}
response = service.spreadsheets().batchUpdate(spreadsheetId=spreadsheet_id,
body=body).execute()
Had kind of the same issue. I was confusing the sheet id with sheet index.
Easiest way to find the sheet id is in the browser URL when you open the spreadsheet / sheet: https://docs.google.com/spreadsheets/d/{spreadsheetId}/edit#gid={sheetId}
If you're looking for a more programmatic way you find that property on the SheetProperties.
I know that's an old question but I was looking for it too. You're looking for:
res.data.sheets[].properties.sheetId
To get the sheetId (not the spreadsheetId) use:
sheets.spreadsheets.get({
spreadsheetId
}).then(res => {
console.log("All the sheets:");
for(i in res.data.sheets) {
let title = res.data.sheets[i].properties.title;
let id = res.data.sheets[i].properties.sheetId;
console.log(title + ': ' + id);
}
});
Make sure that there is a workbook with the id 1 in your spreadsheet. In google sheet, a spreadsheet can contain multiple worksheet(grid), there is a unique id for each of the worksheet(grid).

Google UI Apps Script: Blank PDF when converting spreadsheet to PDF

I have a piece of code I am testing, in an attempt to learn how to convert a spreadsheet into a pdf using Google UI Apps Script. The code creates and writes to the spreadsheet but the pdf attachment is blank. Would appreciate any help to get this to work. Thanks.
var newSpreadsheet = SpreadsheetApp.create("My Test Sheet");
var columnNames = ["First Name", "Last Name", "Department"];
newSpreadsheet.getSheetByName('Sheet1').activate();
var headersRange = newSpreadsheet.getActiveSheet().getRange(1, 1, 1, columnNames.length);
headersRange.setValues([columnNames]);
var pdf = DocsList.getFileById(newSpreadsheet.getId()).getAs('application/pdf').getBytes();
var attach = {fileName:'My Test PDF.pdf',content:pdf, mimeType:'application/pdf'};
// Send email
MailApp.sendEmail("myemail#email.com", "subject", "message", {attachments:[attach]});
You should not use DocList anymore. Use DriveApp instead. Below a solution with little modifications of your code:
function toPdf(id){
SpreadsheetApp.flush();
// var ssDoc = DriveApp.getFileById(SpreadsheetApp.getActiveSpreadsheet().getId());
var ssDoc = DriveApp.getFileById(id);
var pdf = DriveApp.createFile(ssDoc.getAs(MimeType.PDF));
return pdf.getBlob().getBytes();
}
function user2943227(){
var newSpreadsheet = SpreadsheetApp.create("My Test Sheet");
var columnNames = ["First Name", "Last Name", "Department"];
// newSpreadsheet.getSheetByName('Sheet1').activate();
var headersRange = newSpreadsheet.getActiveSheet().getRange(1, 1, 1, columnNames.length);
headersRange.setValues([columnNames]);
// var pdf = DocsList.getFileById(newSpreadsheet.getId()).getAs('application/pdf').getBytes();
var pdf = toPdf(newSpreadsheet.getId());
var attach = {fileName:'My Test PDF.pdf',content:pdf, mimeType:'application/pdf'};
// Send email
MailApp.sendEmail("myemail#email.com", "subject", "message", {attachments:[attach]});
}

Word OLE Automation - delete first page and manipulate header and footer

I am using PHP to start Word Automation and manipulate word documents, but i guess it can be done in all any other language. What i need to do is quite simple, i need to remove the first page and add header and footer.
Here is my code:
$word = new COM('word.applicantion');
$word->Documents->Open('xxx.docx');
$word->Documents[1]->SaveAs($result_file_name, 12);
Any samples?
This is the way you could do it in VBA. This can likely be ported to PHP fairly simply.
Sub RemoveFirstPageAndAddHeaderFooter()
Dim d As Document
Set d = ActiveDocument
Dim pageOne As Range
Set pageOne = d.Bookmarks("\page").Range
pageOne.Select
Selection.Delete
d.Sections(1).Headers(1).Range.Text = "Some text"
d.Sections(1).Footers(1).Range.InlineShapes.AddPicture "C:\beigeplum.jpg", False, True
End Sub
Note on the ...InlineShapes.AddPicture - the onus would be on you to ensure the picture is the right size. If you want more control over this, you would use .Footers(1).Shapes.AddPicture instead as that let's you set the width/height, top/left, etc.
try
{
$word = new COM("word.application") //$word = new COM("C:\x.docx");
or die("couldnt create an instance of word");
//bring word to the front
$word->Visible = 1;
//open a word document
$word->Documents->Open("file.docx");
// remove first page
$range = $word->ActiveDocument->Bookmarks("\page");
$range->Select();
$word->Selection->Delete();
//save the document as docx
$word->Documents[1]->SaveAs("modified_file.docx", 12); // SaveAs('filename', format) // format: 0 - same?, 1 - doc?, 2 - text, 4 - text other encoding
}
catch(Exception $e)
{
echo "error class.document.php - convert_to_docx: $e 20100816.01714";
}
//close word
if($word)
$word->Quit();
//free object resources
//$word->Release();
$word = null;