I want to update a cell in a spreadsheet that is used by a chart, using the Open XML SDK 2.0 (CTP). All the code samples I have found insert new cells. I am struggling with retrieving the right worksheet.
public static void InsertText(string docName, string text, uint rowIndex,
string columnName)
{
// Open the document for editing.
using (SpreadsheetDocument spreadSheet =
SpreadsheetDocument.Open(docName, true))
{
Workbook workBook = spreadSheet.WorkbookPart.Workbook;
WorksheetPart worksheetPart = workBook.WorkbookPart.
WorksheetParts.First();
SheetData sheetData = worksheetPart.Worksheet.
GetFirstChild<SheetData>();
// If the worksheet does not contain a row with the specified
// row index, insert one.
Row row;
if (sheetData.Elements<Row>().Where(
r => r.RowIndex == rowIndex).Count() != 0)
// At this point I am expecting a match for a row that exists
// in sheet1 but I am not getting one
When I navigate the tree in Visual Studio, I am seeing three sheets, but none of them has any children. What am I missing?
This is SDK 2.5 though, however, was very useful code found here: http://fczaja.blogspot.dk/2013/05/how-to-read-and-write-excel-cells-with.html
Needed to do a slight modification for text values to add them to the
SharedStringTablePart
.And use it like this:
public class TextCell : Cell { public TextCell(string header, string text, int index) { this.DataType = CellValues.InlineString; this.CellReference = header + index; //Add text to the text cell. this.InlineString = new InlineString { Text = new Text { Text = text } }; } }
I've been working with excel and found this helper library to be of great help (I've created my own helpers for word, would have saved at least 2 weeks if I was aware of this): http://simpleooxml.codeplex.com/
This is what is needed to update cell (writer.PasteText(...)):
The Code posted by @CDonner throws some exceptions, i have added some of the code that will take care of code, which throws an Exceptions, here it is
}
I made some changes on @AZ code.
First, on GetCell function there is a problem on selecting the current row. Just change:
instead of:
And in the section:
If you are using Columns above Z Column (as AA column, for example) will not work properly. To some this, I'm using the column numbers to determinate where insert the Cell.
For this, I created a function ColumnIndex, with convert the column letters to numbers:
So I changed the string compare function for this:
Best Regards.
Here is the working code. This is a prototype. For a larger number of changes, one might open the document only once. Also, there are some hard-coded things like sheet name and cell type that would have to be parameterized before this can be called production-ready. http://openxmldeveloper.org/forums/4005/ShowThread.aspx was very helpful.