How to access a FormControl checkbox in an Excel sheet using OpenXML SDK - excel

I have a spreadsheet that has a number of check boxes in various cells on the sheet that I need to get the value of (checked/unchecked) from within a c# program.
I'm using the OpenXML SDK v2.5 and the associated toolbox.
Using the toolbox I can see the check box controls as part of the AlternateControlParts collection. These are not ActiveX checkboxes but are form controls added via the developer tab in Excel.
When I use the SDK I can also see the WorkSheetPart which has a ControlPropertiesParts collection on it which lists all the checkboxes.
My problem is, how do I find which checkbox is in which cell or at least related to which cell?
I have also found the collection
wsPart.ControlPropertiesParts.First().DrawingsPart
.WorkSheetDrawing.DrawingsPart.WorkSheetDrawing
This collection appears to have the alternate content of each of the checkboxes and if I drill down further I can find the anchor points which appear to give the location of the checkboxes relative to the cells on the sheet. However, the col and row Id’s don’t appear to exactly match up and I suspect that the Offset values may also have something to do with it.
If someone can point me in the right direction on how to map the checkboxes to the correct row/cells I would be very grateful.
Thank you for any help.
Regards
Paul

I have a solution, it contains only the logic (The property FormControlProperties is available since Office 2010:
SpreadsheetDocument document;
string sheetName = "sheetName";
string controlName = "Option Button 5";
...
var wbPart = document.WorkbookPart;
var theSheet = wbPart.Workbook.Descendants<Sheet>().FirstOrDefault(s => s.Name == sheetName);
var wsPart = (WorksheetPart)wbPart.GetPartById(theSheet.Id);
var control = wsPart.Worksheet.Descendants<DocumentFormat.OpenXml.Spreadsheet.Control>().FirstOrDefault(c => c.Name == controlName);
var controlProperies = (ControlPropertiesPart)wsPart.GetPartById(control.Id);
bool isChecked = controlProperies.FormControlProperties.Checked == "Checked";
But it is simplier to map the FormControl value to a cell and read the cell value if the you can edit the excel file.

Related

Get Excel Sheet Direction with Xlrd

How can check the excel sheet direction with python?. my mean is Left_to_Right or Right_to_Left.
You need to load the workbook using formatting_info parameter like below.
wb = xlrd.open_workbook("table.xls", formatting_info=True)
You can then use wb.xf_list attribute to retrieve formatting information like text_direction. Each cell in the workbook will have have an xf_index attribute allowing you to retrieve corresponding information in the wb.xf_list.
According to the documentation, these are the possible values for the text_direction attribute.
0 = according to context; 1 = left-to-right; 2 = right-to-left

Opening excel file prompts a message box "content recovery of the workbook"

While I'm trying to open excel file a message box is prompting like "We found a problem with some content in file name. Do you want us to try to recover as much as we can? If you trust the source of this workbook, click Yes.". What actually done is i have a excel template designed and copying the file to another file and created temp file I'm inserting data to temp file using OPEN XML and data is getting from the database.
i have tried the solutions provided in the net but those fixes are not resolving my issue.My excel is 2010
Anyone solution provided is much appreciated.
I had this problem. It was caused by the way I was storing numbers and strings in cells.
Numbers can be stored simply using cell.CellValue = new CellValue("5"), but for non-numeric text, you need to insert the string in the SharedStringTable element and get the index of that string. Then change the data type of the cell to SharedString, and set the value of the cell to the index of the string in the SharedStringTable.
// Here is the text I want to add.
string text = "Non-numeric text.";
// Find the SharedStringTable element and append my text to it.
var sharedStringTable = document.WorkbookPart.GetPartsOfType<SharedStringTablePart>().First().SharedStringTable;
var item = sharedStringTable.AppendChild(new SharedStringItem(new Text(text)));
// Set the data type of the cell to SharedString.
cell.DataType = new EnumValue<CellValues>(CellValues.SharedString);
// Set the value of the cell to the index of the SharedStringItem.
cell.CellValue = new CellValue(item.ElementsBefore().Count().ToString());
This is explained in the documentation here: http://msdn.microsoft.com/en-us/library/office/cc861607.aspx
Another few cases that can cause this type of error:
Your sheet name is longer than 31 characters
You have invalid characters in sheet name
You have cells with values longer than 32k
The issue is due to using
package.Save();
and
package.GetAsByteArray();
at the same time
when we call
package.GetAsByteArray();
it will do following operations
this.Workbook.Save();
this._package.Close();
this._package.Save(this._stream);
Hence, removing
package.Save();
will solve this problem "We found a problem with some content in file name. Do you want us to try to recover as much as we can? If you trust the source of this workbook, click Yes."
Another possible cause could be exceeded maximum number of cell styles.
You can define:
up to 4000 styles in a .xls workbook
up to 64000 styles in a .xlsx workbook
In this case you should re-use the same cell style for multiple cells, instead of creating a new cell style for every cell.
I added the right cellReference and fixed this issue for me:
string alpha = "ABCDEFGHIJKLMNOPQRSTUVQXYZ";
for (int colInx = 0; colInx < reader.FieldCount; colInx++)
{
AppendTextCell(alpha[colInx] + "1", reader.GetName(colInx), headerRow);
}
private static void AppendTextCell(string cellReference, string cellStringValue, Row excelRow)
{
// Add a new Excel Cell to our Row
Cell cell = new Cell() { CellReference = cellReference, DataType = new EnumValue<CellValues>(CellValues.String) };
CellValue cellValue = new CellValue();
cellValue.Text = cellStringValue.ToString();
cell.Append(cellValue);
excelRow.Append(cell);
}
Same warning but the problem with me was that I was using a client input (name of wave) as sheet name for the file and when date was presented within the name, the character '/' used as date part separator was causing the issue.
I think Microsoft need to provide a better error log to save people time investigate such minor issues. Hope my answer will save someone else's time.
The issue was due to storing a string in the cell directly using cell.CellValue = new CellValue("Text"). It is possible to store numbers like this but not string. For string, define data type as string before assigning the text using Cell.DataType = CellValues.String;

ColumnCount in DataGridView remains 0 after assigning data source

I am having trouble with the following simple code
BindingList<Car> tempList = new BindingList<Car>();
BindingSource bindingSource = new BindingSource();
bindingSource.DataSource = tempList;
dgTempView.DataSource = bindingSource;
Here, dgTempView is a data grid view
After the above lines execute, the column count in the datagrid view remains 0. And when I try adding a Car instance in tempList, I get an error saying that 'no row can be added to a datagridview control that does not have columns' . I am not able to understand what am I missing here
Found my mistake. The members of the Class Car were public instance variables and not properties. The moment I changed them to Auto Properties it worked :)

How to change datagrid cell fore colors as dynamically using c#

I know this is a stupid question but i can't get my desired out put.Actually i want change the datagridview cell fore colors as dynamically for this i have logic like this
this.dataGridView1.Rows[0].Cells[1].Style.ForeColor = System.Drawing.Color.Red;
but this is not apply to the cell(even cell background also not applied),
But i get the fore color name what i assigned to the cell
string colorname = this.dataGridView1.Rows[0].Cells[1].Style.ForeColor.Name;
.Is there any mistake in my query please help me.
Check this
dataGridView1[col, row].Style.ForeColor = Color.Blue;
I hope This help!
To customize the styles of cells with particular values, implement a handler for the DataGridView.CellFormatting event. Handlers for this event receive an argument of the DataGridViewCellFormattingEventArgs type. This object contains properties that let you determine the value of the cell being formatted along with its location in the DataGridView control. This object also contains a CellStyle property that is initialized to the value of the InheritedStyle property of the cell being formatted. You can modify the cell style properties to specify style information appropriate to the cell value and location.
From MSDN
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (e.ColumnIndex == 0 && e.RowIndex == 0)
e.CellStyle.ForeColor = Color.Red;
}
The result is provided below:
Insert preferred indices instead of zeros in if statement to change ForeColor of only those cells that you need.

How to get the value in an Excel dropdown using C#

I am looking for code to open and read an Excel file, any version of Excel, including 2010. One of my columns has a dropdown in it. I need to get the value of the selected item in the dropdown. I would eventually want to populate these values into a business object.
If anyone has some code to share please let me know.
I am using C# and Visual Studio 2010.
Thanks.
I know the VBA for both the ActiveX combo and the forms dropdown, and based on that, I can give you some very inexpert notes for c# for the forms dropdown, the combo eludes me as yet.
Working with notes from: http://support.microsoft.com/kb/302084
//Get a new workbook.
oWB = (Excel._Workbook)(oXL.Workbooks.Open("C:\\Docs\\Book1.xls"));
//3rd Sheet
oSheet = (Excel._Worksheet)oWB.Sheets.get_Item(3);
//This will return an index number
var i = oSheet.Shapes.Item("Drop Down 1").ControlFormat.Value;
//This will return the fill range
var r = oSheet.Shapes.Item("Drop Down 1").ControlFormat.ListFillRange;
oRng = oSheet.get_Range(r);
//This will return the value of the dropdown, based on the index
//and fillrange
var a =oRng.get_Item(i).Value;
//Just to check
textBox1.Text = a;
This may help with an ActiveX combo, but I have only half got it to work:
using MSForm = Microsoft.Vbe.Interop.Forms;
<...>
Excel.OLEObject cbOLEObj = (Excel.OLEObject)workSheet.OLEObjects("ComboBox1");
MSForm.ComboBox ComboBox1 = (MsForm.ComboBox) cbOLEObj.Object;
Console.WriteLine(ComboBox1.Text);
From: http://www.eggheadcafe.com/community/aspnet/66/10117559/excel-get-value-from-a-combobox.aspx

Resources