I was trying to create an Excel button in a sheet from a C# code, using a C# event hander for the button, so I don't have to involve VBA and text scripts; and I found this great solution from #
Dummy yoyo that works but "only for a while".
The solution is simple: add a shape, get it as an ole object, get the ole as a button and add a click event:
int i = 1;
private void CreateButton()
{
Microsoft.Office.Interop.Excel.Worksheet sheet = #get a sheet from Excel
sheet.Shapes.AddOLEObject("Forms.CommandButton.1", Type.Missing, false, false, Type.Missing, Type.Missing, Type.Missing, 10, 10, 100, 30);
Microsoft.Office.Interop.Excel.OLEObject oleShape = sheet.OLEObjects(1);
Microsoft.Vbe.Interop.Forms.CommandButton button = oleShape.Object;
button.Caption = "Custom Buttom" + i;
button.Click += Button_Click;
i++; //for future use, see below
}
private void Button_Click()
{
MessageBox.Show("It works!");
}
The problem:
Now, the first time I click the button on the sheet, it works! The second time "might" work. The more clicks the less chance of it working. Inevitably, the button "loses" the click event and just does nothing. I can't figure out why, what can be causing this.
I even tried to recreate the button every click with:
private void Button_Click()
{
MessageBox.Show("It Works!");
sheet.Shapes.Item(1).Delete();
CreateButton();
}
I can see the button is being recreated because of the i++ that shows in the button's caption. Even though, some clicks later, even the newly created button simply does nothing when clicked.
What can be going on? How can I solve this?
Edit:
A partial solution was found, as #Hans Passant suggested: if I keep the shape, the ole object and the button as static members outside the method, the garbage collector doesn't kill them. Nevertheless, I would like to save, close and reopen the sheet and still get the events.
Great solutions could be:
Identifying why it happens and solving it
Suggesting another way of creating the button using a c# click handler
Making it possible to save this sheet, close and reopen it with the events still attached.
A few more details:
I am creating a new Excel application from C# code and taking the first sheet of the first workbook.
This is not a VSTO Addin, I don't have access to the Globals.Factory, although I'd love to be able to get an instance of this factory and try Microsoft.Office.Tools.Worksheet methods to add controls.
My project is inevitably a class library consumed by another non-related software
The sheet must be saved and reopened later independently from the source project.
The sheet is populated before adding the button, also via C# code.
Visual Studio debugger is able to step into the button's event handler without any special action
Following way every time I click on this button not getting any issue.
using Excel = Microsoft.Office.Interop.Excel;
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
int i = 1;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
//add data
xlWorkSheet.Cells[1, 1] = "";
xlWorkSheet.Cells[1, 2] = "Student1";
xlWorkSheet.Cells[1, 3] = "Student2";
xlWorkSheet.Cells[1, 4] = "Student3";
xlWorkSheet.Cells[2, 1] = "Term1";
xlWorkSheet.Cells[2, 2] = "80";
xlWorkSheet.Cells[2, 3] = "65";
xlWorkSheet.Cells[2, 4] = "45";
xlWorkSheet.Cells[3, 1] = "Term2";
xlWorkSheet.Cells[3, 2] = "78";
xlWorkSheet.Cells[3, 3] = "72";
xlWorkSheet.Cells[3, 4] = "60";
xlApp.Visible = true;
#region
xlWorkSheet.Shapes.AddOLEObject("Forms.CommandButton.1", Type.Missing, false, false, Type.Missing, Type.Missing, Type.Missing, 10, 10, 100, 30);
Microsoft.Office.Interop.Excel.OLEObject oleShape = xlWorkSheet.OLEObjects(1);
Microsoft.Vbe.Interop.Forms.CommandButton button = oleShape.Object;
button.Caption = "Custom Buttom" +i ;
button.Click += Button_Click;
i++;
#endregion
}
private void Button_Click()
{
MessageBox.Show("It works!");
}
but sometime button seems not clickable or not fire click even. see below screenshot.
Message show already, but we do not see it in top of the worksheet. too many time click on the button it may happened. so if you do not see the dialog just open it from taskbar.
Reopen: Controls that are added at run time are not persisted when the document or workbook is saved and closed. The exact behavior is different for host controls and Windows Forms controls. In both cases, you can add code to your solution to re-create the controls when the user reopens the document.
xlApp = new Excel.Application();
string workbookPath = #"c:/Book.xlsx";
xlWorkBook = xlApp.Workbooks.Open(workbookPath,
0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "",
true, false, 0, true, false, false);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlApp.Visible = true;
Microsoft.Office.Interop.Excel.OLEObject oleShape = xlWorkSheet.OLEObjects(1);
Microsoft.Vbe.Interop.Forms.CommandButton button = oleShape.Object;
button.Caption = "Custom Buttom" + i;
button.Click += Button_Click;
i++;
NB: Microsoft Excel 2013, project reference Microsoft office 15.0 object Library and VS 2022 work perfectly but Excel 2016 has this issue you are telling about. so I think this issue has come from
Microsoft Office specific version.
if you want to make it count clicks try this..
const btn = document.querySelector('.btn');
btn.onclick = Counter;
const clicks = document.querySelector('.clicks');
clicks.id = document.querySelector('clicks');
var a = 0;
function Counter() {
a += 1;
clicks.innerHTML = a;
}
const reset = document.querySelector('.reset');
reset.onclick = resetCounter;
function resetCounter() {
a = 0;
clicks.innerHTML = a;
}
I am creating charts in PowerPoint. The below code opens two excel applications. One opens in the background that is invisible. The second one opens after the method ends. I need to make sure second excel either never open ideally or I can close it after it opens.
I have tried the below things but none worked.
I have tried forcing GC, Manual ReleaseComObject, Killing Excel process
I have tried separating excel COM objects and forcing GC
private void BtnInsert_Click(object sender, EventArgs e)
{
var Addin = Globals.ThisAddIn;
Microsoft.Office.Interop.PowerPoint.Application activeApplication = Addin.Application;
DocumentWindow activeWindows = activeApplication.ActiveWindow;
Microsoft.Office.Interop.PowerPoint.View activeView = activeWindows.View;
Slide activeSlide = activeView.Slide;
Microsoft.Office.Interop.PowerPoint.Shapes slideShape = activeSlide.Shapes;
Microsoft.Office.Interop.PowerPoint.Shape shape = slideShape.AddChart2(-1, XlChartType.xl3DBarClustered, -1, -1, -1, -1, true);
Microsoft.Office.Interop.PowerPoint.Chart chart = shape.Chart;
//Access the chart data
Microsoft.Office.Interop.PowerPoint.ChartData chartData = chart.ChartData;
chartData.Activate();
//Create instance to Excel workbook to work with chart data
Workbook workbook = chartData.Workbook;
Microsoft.Office.Interop.Excel.Application workbookApplication = workbook.Application;
workbookApplication.Visible = false;
workbookApplication.WindowState = XlWindowState.xlMinimized;
//Accessing the data worksheet for chart
Worksheet worksheet = workbook.Worksheets[1];
// I am adding data here
// This is not required to reproduce this
chartData.BreakLink();
workbook.Close(true);
}
Also, note that this issue does not occur while updating data.
Remove chartData.Activate() and chartData.BreakLink() solves this.
Although online documentation says that chartdata.activate is required before accessing the workbook.
Otherwise, we will get a null reference.
I think the documentation is incorrect or it does not apply to vsto.
This image show what i basically want to do
I have plenty excel files that i need to prepare before inserting the data into a SQL database, one of the steps is unmerge excel cells and duplicate the data, i'm doing this doc parse with c#
I found a solution with VBA Macro Excel here
Sub UnMergeFill()
Dim cell As Range, joinedCells As Range
For Each cell In ThisWorkbook.ActiveSheet.UsedRange
If cell.MergeCells Then
Set joinedCells = cell.MergeArea
cell.MergeCells = False
joinedCells.Value = cell.Value
End If
Next
End Sub
But i need to do it on c# with microsoft.office.interop.excel
Does anyone know if there's a way to do this?
C# code is very similar:
private void UnMergeFill(Workbook wb)
{
foreach (Range cell in ((_Worksheet)wb.ActiveSheet).UsedRange)
{
if (cell.MergeCells)
{
var joinedCells = cell.MergeArea;
cell.MergeCells = false;
joinedCells.Value = cell.Value;
}
}
}
I am looking for a way to move my selected cell from the top left to the bottom right. I was trying to use xlDirection but that highlights everything and doesnt allow me to do a combination of movements.
A B C
1 4 7
2 5 8
3 6 9
I start at A and now only want to focus on 9. The size of the excels change so i cant specify the actual cell to look for each time.
I was hoping there are similar commands as Ctrl+Down or Ctrl+Right that would put me on the cell.
can't you send keystrokes to the object?
A reference for all key strokes can be found here:
https://learn.microsoft.com/en-us/dotnet/api/microsoft.office.interop.excel._application.sendkeys?view=excel-pia
public class Navigator
{
private Excel.Application excel;
private Excel.Workbook workbook;
public void NavigateToBottomRight(string filePath, string worksheetName)
{
excel = new Excel.Application();
excel.Visible = true;
workbook = excel.Workbooks.Open(filePath);
var worksheet = workbook.Worksheets.Cast<Excel.Worksheet>().FirstOrDefault(x => x.Name == worksheetName);
Excel.Range cell = worksheet.Cells[1, 1];
cell.Activate();
string controlRight = "^{Right}";
string controlDown = "^{Down}";
excel.SendKeys(controlRight, true);
excel.SendKeys(controlDown, true);
//Do other work here
workbook.Save();
excel.Quit();
}
}
Hope this helps!
A year ago I saw a beautiful simple code that gets a data table and saves it in an excel file.
The trick was to use the web library (something with http) and I'm almost sure it was a stream.
I find a lot of code with response but I can't make it work in a win-form environment.
There is also a cell by cell code - not interested -too slow.
I want to paste it as a range or something close.
Thanks
I believe this is the code you're looking for:
DataTable to Excel
It uses an HtmlTextWriter.
There are many component libraries out there that will provide this kind of functionality.
However, you could probably, most simply output the data as a CSV file and the load that into Excel.
What I like to do is put the datatable in a grid allowing the user to sort and filter. Then they can use the clipboard to copy/paste to Excel.
Private Sub mnuCopy_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuCopy.Click
If dgvDisplaySet.GetClipboardContent Is Nothing Then
MsgBox("Nothing selected to copy to clipboard.")
Else
Clipboard.SetDataObject(dgvDisplaySet.GetClipboardContent)
End If
End Sub
Thanks all especially Jay
my old code just as you suggested is:
at least the next time it will wait for me here ;)
private void cmdSaveToExcel_Click(object sender, EventArgs e)
{
saveFileDialog1.Filter = "Excel (*.xls)|*.xls";
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
txtPath.Text = saveFileDialog1.FileName;
}
// create the DataGrid and perform the databinding
System.Web.UI.WebControls.DataGrid grid = new System.Web.UI.WebControls.DataGrid();
grid.HeaderStyle.Font.Bold = true;
if (connDBs != null && rtxtCode.Text != "")
{
DataTable dt;
dt = connDBs.userQuery(rtxtCode.Text); // getting a table with one column of the databases names
//grdData.DataSource = dt;
grid.DataSource = dt;
// grid.DataMember = data.Stats.TableName;
grid.DataBind();
// render the DataGrid control to a file
using (StreamWriter sw = new StreamWriter(txtPath.Text))
{
using (HtmlTextWriter hw = new HtmlTextWriter(sw))
{
grid.RenderControl(hw);
}
}
MessageBox.Show("The excel file was created successfully");
}
else
{
MessageBox.Show("Missing connection or query");
}
}
You need to convert your datatable into a ADO recordset, and then you can use the Range object's CopyFromRecordset method. See http://www.codeproject.com/KB/database/DataTableToRecordset.aspx