How to change the Selection activecell in sheetview using OpenXml? - c#

I need to remove this Selection activecell and it can be done by assigning it to A1. But I could not figure out the tag hierarchy I should be using.
I used the following code.But it is not working.
WorkbookPart wbPart = doc.WorkbookPart;
var workbook = doc.WorkbookPart.Workbook;
WorksheetPart worksheetPart = wbPart.WorksheetParts.First();
Worksheet worksheet = worksheetPart.Worksheet;
SheetViews sheetViews = worksheet.SheetViews;
SheetView sheetView = sheetViews.Descendants<SheetView>().First();
var selection = sheetView.Descendants<Selection>().First();
selection.ActiveCell = "A1";

If all you want to do is the remove the selected cell then you just need to replace your last two lines with
sheetView.RemoveAllChildren();
IF you also want to make sure that A1 is the top left cell in view then you should also add the following line
sheetView.TopLeftCell = "A1";
Also be sure to save the worksheet with
worksheet.Save();

Related

How to check Self Referencing cell formula in excel using OpenXML

Is there any way to find out Self Referencing cell formula in excel using OpenXML C#. I didn't recognize how to find out Self Referencing cell formula. For e.g Cell C3 has formula =SUM(C1:C5). How to recognize this formula had self Referencing cell? or Can I can get all cell names from this formula?
My code is:
SpreadsheetDocument excelDocument = SpreadsheetDocument.Open(FilePath, true);
WorkbookPart wbPart = excelDocument.WorkbookPart;
string sheetId = wbPart.Workbook.Descendants<Sheet>().First().Id;
WorksheetPart wsPart = (WorksheetPart)(wbPart.GetPartById(sheetId));
IEnumerable<Cell> theCells = wsPart.Worksheet.Descendants<Cell>();
foreach (Cell thecell in theCells)
{
string strFormula = thecell.CellFormula.InnerText;
}

Can not read spread sheet cell with different font in C#

A spread sheet contains 5 columns and 8 rows. First row is the header of the sheet. I have to read all the data of the cells. The last column contains blank value. C# is unable to read the 5th column of 7th and 8th row. The below code returns array index out of bound exception.
rows[7].Descendants().ElementAt(4)
I have found that the font size of 5th column of rows 7th and 8th are different from the other. If I have changed the font size then it is working fine. I don't have any explanation for this unnatural behaviour.
Please find the code base below
using (SpreadsheetDocument spreadSheetDocument = SpreadsheetDocument.Open(filePath, false))
{
WorkbookPart workbookPart = spreadSheetDocument.WorkbookPart;
var workBookSheet = spreadSheetDocument.WorkbookPart.Workbook.GetFirstChild<Sheets>().Elements<Sheet>().Where(s => s.Name.ToString() == "Feuil1").FirstOrDefault();
if (workBookSheet != null)
{
string relationshipId = workBookSheet.Id.Value;
WorksheetPart worksheetPart = (WorksheetPart)spreadSheetDocument.WorkbookPart.GetPartById(relationshipId);
Worksheet workSheet = worksheetPart.Worksheet;
SheetData sheetData = workSheet.GetFirstChild<SheetData>();
IEnumerable<Row> rows = sheetData.Descendants<Row>();
var data = rows.ElementAt(2).Descendants<Cell>().ElementAt(4);
}
}
The spreadsheet looks like below -
enter image description here
As per the sheet I have got error on row 3 column 4.
Try this to get the value
string val = (Range)xlWorkSheet.Cells[7, 5]).Value2.ToString();

Aspose workbook copy/rename sheet

I want to Copy Sheet from excel, create copy of sheet with particular name.
Aspose.Cells.Workbook workbook = new Aspose.Cells.Workbook(excelFilePath);
//Create a Worksheets object with reference to the sheets of the Workbook.
WorksheetCollection sheets = workbook.Worksheets;
sheets.AddCopy("Cash Bonuses");
Now the problem is it copies data of Sheet "Cash Bonuses" but it makes Sheet name as "Sheet111". I want to make this sheet with specified name like "Cash".How to do that ? Once data is copied to new tab , i want to delete old tab "Cash Bonuses" and rename new tab as "Cash bonuses" from "Cash".
Please note, in order to copy the contents of a worksheet to another worksheet, you need to add a blank worksheet to the collection and then call its Copy method while passing the object of existing worksheet (one that needs to be copied) otherwise you will lose data on the destination worksheet.
Please try the following piece of code as it tries to accomplish all your requirements. Hopefully, the comments will help you understand what the statements mean.
var workbook = new Aspose.Cells.Workbook(excelFilePath);
var sheets = workbook.Worksheets;
//Access 1st worksheet from the collection
//You may also pass the worksheet name to access a particular worksheet
var sheet0 = sheets[0];
//Add a new worksheet to the collection and name it as desired
var sheet1 = sheets[sheets.Add()];
sheet1.Name = "Cash";
//Copy the contents of 1st worksheet onto the new worksheet
sheet1.Copy(sheet0);
//Delete 1st worksheet
sheets.RemoveAt(sheet0.Index);
//Rename newly added worksheet to 'Cash bonuses'
sheet1.Name = "Cash bonuses";
//Save result
workbook.Save(dir + "output.xlsx");
Note: I work with Aspose as Developer Evangelist.

OpenXml WorksheetParts.First() is not always the 1st sheet MS Excel shows

I have XLSX files which when viewed in Excel have multiple sheets.
However, some of the files using the snippet below actually have the WorksheetPart.First as the 2nd or 3rd worksheet when viewed in excel. I think this is because the sheets were re-arranged in excel at one point.
Q: How to use OpenXml to read the sheets in the "view" order that MS-Excel shows them in, versus what can be out of order via OpenXml? Note: I can't use sheet name as a workaround.
using (var document = SpreadsheetDocument.Open(".\test.xlsx", false))
{
var workbookPart = document.WorkbookPart;
var worksheetPart = workbookPart.WorksheetParts.First();
// worksheetPart is not always the first worksheet that Excel shows
}
I guess the worksheet parts are not necessarily in order. What should be in order though is the Workbook.Sheets property (you can also search by name here). You can correlate a Sheet with its WorksheetPart through it's Id, see here for example.
I hope, this way you will get the right worksheetpart for the sheet index.
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using System.Linq;
// ----------------------------------------------------------------------
using (SpreadsheetDocument xl = SpreadsheetDocument.Open(fileName, false))
{
int sheetNo = 0; // Index 0 => sheet 1
WorkbookPart wbPart = xl.WorkbookPart;
Sheet sheet = wbPart.Workbook
.Descendants<Sheet>()
.ElementAt(sheetNo);
WorksheetPart wsPart = (WorksheetPart)(wbPart.GetPartById(sheet.Id));
}

Inserting formula giving error.. Excel found unreadable content in "ab.xlsx". Do you want to recover the

my requirement to is to insert formula for a cell. i am using below method to insert formula. And its inserting formula corectly and formula working fine.
but when i insert formula my excel file got corrpted and showing the message
"Excel found unreadable content in "exceltemplate.xlsx"
Do you want to recover the contents of...".
I searched lot,but not getting resolved.
Please help to resolve this
public void InsertFormula(string filepath, string SheetName, string strCellIndex, string strFormula)
{
using (SpreadsheetDocument document = SpreadsheetDocument.Open(filepath, true))
{
IEnumerable<Sheet> sheets = document.WorkbookPart.Workbook.Descendants<Sheet>().Where(s => s.Name == SheetName);
if (sheets.Count() == 0)
{
// The specified worksheet does not exist.
return;
}
WorksheetPart worksheetPart = (WorksheetPart)document.WorkbookPart.GetPartById(sheets.First().Id);
Worksheet worksheet = worksheetPart.Worksheet;
SheetData sheetData = worksheet.GetFirstChild<SheetData>();
Row row1 = new Row()
{
RowIndex = (UInt32Value)4U,
Spans = new ListValue<StringValue>()
};
Cell cell = new Cell() { CellReference = strCellIndex };
CellFormula cellformula = new CellFormula();
cellformula.Text = strFormula;
cell.DataType = CellValues.Number;
CellValue cellValue = new CellValue();
cellValue.Text = "0";
cell.Append(cellformula);
cell.Append(cellValue);
row1.Append(cell);
sheetData.Append(row1);
worksheet.Save();
document.Close();
}
}
There are 2 problems with the function.
1st problem is that you explicitly set the RowIndex to 4U. The cell that you're assigning the formula to has to be on row 4, say cell C4. Since the cell reference is passed in as a parameter (strCellIndex), that's not guaranteed.
And even if you fixed that, we have the next (and more insidious) problem...
2nd problem is a little harder to fix. The Row class has to be inserted in order within the SheetData class (as child objects), ordered by RowIndex. Let's assume you still want RowIndex to be hard-coded as 4U. This means if the existing Excel file has rows 2, 3 and 7, you have to insert the Row class behind the Row class with RowIndex 3. This is important, otherwise Excel will puke blood (as you've already experienced).
The solution to the 2nd problem requires a little more work. Consider the functions InsertAt(), InsertBefore() and InsertAfter() of the SheetData class (or most of the Open XML SDK classes actually). Iterate through the child classes of SheetData till you find a Row class with a RowIndex greater than the Row class you're inserting. Then use InsertBefore().
I will leave you with the fun task of error checking, such as if there are no Row classes to begin with, or all Row classes have RowIndex-es less than your to-be-inserted Row class, or (here's the fun one) an existing Row class with the same RowIndex as the Row class you want to insert.

Categories